<commit_before>var selectedShow;
var selectedSeats = [];
var adultSeatsAmount = 0;
var studentSeatsAmount = 0;

$(document).ready(initShows);

$('body').on('click', '.show-selection-link', function(e) {
    e.preventDefault();

    var selectedShowId = Number($(this).find('div').attr('id').replace('show-', ''));

    $.ajax({
        type: 'GET',
        url: '/api/v1/shows/' + selectedShowId,
        dataType: 'JSON',
        success: function(data) {
            selectedShow = data;

            getTemplate('/views/partials/seatselection.ejs', function(err, template) {
                var seatSelection = ejs.render(template, {show: selectedShow, time: new Date(data.time)});
                $('#content').html(seatSelection);
                $('.breadcrumb li:eq(1)').toggleClass('active');
                initSeatCharts();
            });
        }
    });
}).on('click', '#checkout-button', function(e) {
    e.preventDefault();

    $('#checkout-button').popover({
        trigger: 'manual',
        placement: 'left',
        container: 'body'
    });

    adultSeatsAmount = parseInt($('#adultTickets').val());
    studentSeatsAmount = parseInt($('#studentTickets').val());

    if (selectedSeats.length <= 0) {
        $(this).data('bs.popover').options.content = 'Please select your seats first.';
        $(this).popover('show');
        setTimeout(function() {
            $('#checkout-button').popover('hide');
        }, 3000);
        return;
    } else if (selectedSeats.length !== adultSeatsAmount + studentSeatsAmount) {
        $(this).data('bs.popover').options.content = 'Please ensure that the number of seats selected matches the number of people in your group.';
        $(this).popover('show');
        setTimeout(function() {
            $('#checkout-button').popover('hide');
        }, 3000);
        return;
    }

    getTemplate('/views/partials/checkout.ejs', function(err, template) {
        var checkout = ejs.render(template, {
            selectedSeats: selectedSeats,
            show: selectedShow,
            time: new Date(selectedShow.time),
            adultSeatsAmount: adultSeatsAmount,
            studentSeatsAmount: studentSeatsAmount,
            totalPrice: (studentSeatsAmount * selectedShow.studentprice) + (adultSeatsAmount * selectedShow.adultprice)
        });
        $('#content').html(checkout);
        $('.breadcrumb li:eq(2)').toggleClass('active');

        // Braintree Setup
        $.ajax({
            type: 'GET',
            url: '/api/v1/token',
            dataType: 'JSON',
            success: function(data) {
                braintree.setup(data.clientToken, 'custom', {
                    id: 'payment-form',
                    onReady: function() {
                        $('.spinner').remove();
                        $('#payment-form').removeClass('hidden');
                    },
                    onPaymentMethodReceived: function(obj) {
                        $.ajax({
                            type: 'GET',
                            url: '/api/v1/shows/' + selectedShow + '/purchased_seats',
                            dataType: 'JSON',
                            success: function(data) {
                                var seats = selectedSeats.join(',');
                                var problem = false;
                                data.forEach(function(purchasedSeat) {
                                    if (seats.indexOf(purchasedSeat) == -1) {
                                        problem = true;
                                    }
                                });

                                if (!problem) {
                                    $.ajax({
                                        type: 'POST',
                                        url: '/api/v1/checkout',
                                        dataType: 'JSON',
                                        data: {
                                            seats: $('input[name=seats]').val(),
                                            price: (studentSeatsAmount * selectedShow.studentprice) + (adultSeatsAmount * selectedShow.adultprice),
                                            showid: $('input[name=showid]').val(),
                                            showname: $('input[name=showname]').val(),
                                            paymentMethodNonce: obj['nonce'],
                                            firstName: $('input[name=firstName]').val(),
                                            lastName: $('input[name=lastName]').val(),
                                            email: $('input[name=email]').val(),
                                            phone: $('input[name=phone]').val(),
                                            address: $('input[name=address]').val(),
                                            city: $('input[name=city]').val(),
                                            state: $('input[name=state]').val(),
                                            zip: $('input[name=zip]').val()
                                        },
                                        success: function(data) {
                                            getTemplate('/views/partials/confirmation.ejs', function(err, template) {
                                                var confirmation = ejs.render(template, {
                                                    confirmationNumber: data.confirmationNumber,
                                                    show: selectedShow,
                                                    time: new Date(selectedShow.time)
                                                });
                                                $('#content').html(confirmation);
                                                $('.breadcrumb li:eq(3)').toggleClass('active');
                                            });
                                        }
                                    });
                                } else {
                                    // TODO: Alert user of error
                                }
                            }
                        });
                    },
                    hostedFields: {
                        number: {
                            selector: '#card-number',
                            placeholder: 'Credit Card Number'
                        },
                        cvv: {
                            selector: '#cvv',
                            placeholder: 'CVV'
                        },
                        expirationDate: {
                            selector: '#expiration-date',
                            placeholder: 'MM/YY'
                        },
                        styles: {
                            'input': {
                                'font-family': '"Helvetica Neue", Helvetica, Arial, sans-serif',
                                'font-size': '14px'
                            },
                            '::-moz-placeholder': {'color': '#999'},
                            ':-ms-input-placeholder': {'color': '#999'},
                            '::-webkit-input-placeholder': {'color': '#999'}
                        }
                    }
                });
            }
        });

        $('#secure-popover-text').popover({
            trigger: 'hover focus',
            content: 'All credit card information is processed by our external provider, BrainTree (a PayPal company), and fully encrypted every step of the way.',
            html: true,
            placement: 'right',
            container: 'body',
            delay: {
                'show': 100,
                'hide': 600
            }
        });
    });
}).on('click', '#seats-goback-button', function(e) {
    e.preventDefault();

    selectedSeats = [];
    selectedShow = null;

    getTemplate('/views/partials/showselection.ejs', function(err, template) {
        var showSelection = ejs.render(template);
        $('#content').html(showSelection);
        $('.breadcrumb li:eq(1)').toggleClass('active');
        initShows();
    });
}).on('click', '#checkout-goback-button', function(e) {
    e.preventDefault();

    selectedSeats = [];

    getTemplate('/views/partials/seatselection.ejs', function(err, template) {
        var seatSelection = ejs.render(template, {show: selectedShow, time: new Date(selectedShow.time)});
        $('#content').html(seatSelection);
        $('.breadcrumb li:eq(2)').toggleClass('active');
        initSeatCharts();
    });
}).on('click', '#student-info-button', function(e) {
    e.preventDefault();
});

function getTemplate(file, callback) {
    $.ajax(file, {
        type: 'GET',
        success: function(data, textStatus, xhr) {
            return callback(null, data);
        },
        error: function(xhr, textStatus, error) {
            return callback(error);
        }
    });
}

function initShows() {
    $.ajax({
        type: 'GET',
        url: '/api/v1/shows',
        dataType: 'JSON',
        success: function(data) {
            var showSelectionContainer = $('#show-selection-container');

            $('.spinner').remove();
            showSelectionContainer.removeClass('hidden');

            var html = '';
            data.forEach(function(show) {
                var time = new Date(show.time);
                html += '

' +
                    show.name + '

' + (time.getMonth() + 1) + '/'
                    + time.getDate() + '/'
                    + time.getFullYear() + ' '
                    + ((time.getHours() + 24) % 12 || 12) + ':'
                    + ('0' + time.getMinutes()).slice(-2)
                    + ((time.getHours() >= 12) ? 'PM' : 'AM') + '

';
            });
            showSelectionContainer.html(html);
        }
    });
}

function initSeatCharts() {
    $('#student-info-button').popover({
        trigger: 'hover focus',
        content: 'Anyone currently enrolled in school is a student. Children ages 5 and under are free.',
        placement: 'right',
        container: 'body',
        delay: {
            'show': 100,
            'hide': 600
        }
    });

    $.ajax({
        type: 'GET',
        url: '/api/v1/shows/' + selectedShow.id + '/purchased_seats',
        dataType: 'JSON',
        success: function(seats) {
            var seatMap = $('#seat-map');

            $('.spinner').remove();
            seatMap.removeClass('hidden');

            var seatChart = seatMap.seatCharts({
                map: [
                    '__aaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaa__',
                    'aaaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaaa',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '__aaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaa__'
                ],
                naming: {
                    columns: ['37', '35', '33', '31', '29', '27', '25', '23', '21', '19', '17', '15', '13', '11', '9', '7', '5', '3', '1', '', '2', '4', '6', '8', '10', '12', '14', '16', '18', '20', '22', '24', '26', '28', '30', '32', '34', '36', '38'],
                    rows: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
                },
                seats: {
                    a: {
                        classes: 'general'
                    }
                },
                click: function() {
                    if (this.status() === 'available' && selectedSeats.length < (parseInt($('#adultTickets').val()) + parseInt($('#studentTickets').val()))) {
                        // Add to array
                        selectedSeats.push(this.node()[0].id);
                        // Update counter
                        $('#seat-number').text(selectedSeats.length);
                        // Update status
                        return 'selected';
                    } else if (this.status() === 'selected') {
                        // Remove from array
                        selectedSeats.splice(selectedSeats.indexOf(this.node()[0].id), 1);
                        // Update counter
                        $('#seat-number').text(selectedSeats.length);
                        // Update status
                        return 'available';
                    } else if (this.status() === 'unavailable') {
                        return 'unavailable';
                    } else {
                        return this.style();
                    }
                }
            });

            seatChart.get(seats).status('unavailable');
        }
    });
}<commit_msg>fix other thing<commit_after>var selectedShow;
var selectedSeats = [];
var adultSeatsAmount = 0;
var studentSeatsAmount = 0;

$(document).ready(initShows);

$('body').on('click', '.show-selection-link', function(e) {
    e.preventDefault();

    var selectedShowId = Number($(this).find('div').attr('id').replace('show-', ''));

    $.ajax({
        type: 'GET',
        url: '/api/v1/shows/' + selectedShowId,
        dataType: 'JSON',
        success: function(data) {
            selectedShow = data;

            getTemplate('/views/partials/seatselection.ejs', function(err, template) {
                var seatSelection = ejs.render(template, {show: selectedShow, time: new Date(data.time)});
                $('#content').html(seatSelection);
                $('.breadcrumb li:eq(1)').toggleClass('active');
                initSeatCharts();
            });
        }
    });
}).on('click', '#checkout-button', function(e) {
    e.preventDefault();

    $('#checkout-button').popover({
        trigger: 'manual',
        placement: 'left',
        container: 'body'
    });

    adultSeatsAmount = parseInt($('#adultTickets').val());
    studentSeatsAmount = parseInt($('#studentTickets').val());

    if (selectedSeats.length <= 0) {
        $(this).data('bs.popover').options.content = 'Please select your seats first.';
        $(this).popover('show');
        setTimeout(function() {
            $('#checkout-button').popover('hide');
        }, 3000);
        return;
    } else if (selectedSeats.length !== adultSeatsAmount + studentSeatsAmount) {
        $(this).data('bs.popover').options.content = 'Please ensure that the number of seats selected matches the number of people in your group.';
        $(this).popover('show');
        setTimeout(function() {
            $('#checkout-button').popover('hide');
        }, 3000);
        return;
    }

    getTemplate('/views/partials/checkout.ejs', function(err, template) {
        var checkout = ejs.render(template, {
            selectedSeats: selectedSeats,
            show: selectedShow,
            time: new Date(selectedShow.time),
            adultSeatsAmount: adultSeatsAmount,
            studentSeatsAmount: studentSeatsAmount,
            totalPrice: (studentSeatsAmount * selectedShow.studentprice) + (adultSeatsAmount * selectedShow.adultprice)
        });
        $('#content').html(checkout);
        $('.breadcrumb li:eq(2)').toggleClass('active');

        // Braintree Setup
        $.ajax({
            type: 'GET',
            url: '/api/v1/token',
            dataType: 'JSON',
            success: function(data) {
                braintree.setup(data.clientToken, 'custom', {
                    id: 'payment-form',
                    onReady: function() {
                        $('.spinner').remove();
                        $('#payment-form').removeClass('hidden');
                    },
                    onPaymentMethodReceived: function(obj) {
                        $.ajax({
                            type: 'GET',
                            url: '/api/v1/shows/' + selectedShow.id + '/purchased_seats',
                            dataType: 'JSON',
                            success: function(data) {
                                var seats = selectedSeats.join(',');
                                var problem = false;
                                data.forEach(function(purchasedSeat) {
                                    if (seats.indexOf(purchasedSeat) == -1) {
                                        problem = true;
                                    }
                                });

                                if (!problem) {
                                    $.ajax({
                                        type: 'POST',
                                        url: '/api/v1/checkout',
                                        dataType: 'JSON',
                                        data: {
                                            seats: $('input[name=seats]').val(),
                                            price: (studentSeatsAmount * selectedShow.studentprice) + (adultSeatsAmount * selectedShow.adultprice),
                                            showid: $('input[name=showid]').val(),
                                            showname: $('input[name=showname]').val(),
                                            paymentMethodNonce: obj['nonce'],
                                            firstName: $('input[name=firstName]').val(),
                                            lastName: $('input[name=lastName]').val(),
                                            email: $('input[name=email]').val(),
                                            phone: $('input[name=phone]').val(),
                                            address: $('input[name=address]').val(),
                                            city: $('input[name=city]').val(),
                                            state: $('input[name=state]').val(),
                                            zip: $('input[name=zip]').val()
                                        },
                                        success: function(data) {
                                            getTemplate('/views/partials/confirmation.ejs', function(err, template) {
                                                var confirmation = ejs.render(template, {
                                                    confirmationNumber: data.confirmationNumber,
                                                    show: selectedShow,
                                                    time: new Date(selectedShow.time)
                                                });
                                                $('#content').html(confirmation);
                                                $('.breadcrumb li:eq(3)').toggleClass('active');
                                            });
                                        }
                                    });
                                } else {
                                    // TODO: Alert user of error
                                }
                            }
                        });
                    },
                    hostedFields: {
                        number: {
                            selector: '#card-number',
                            placeholder: 'Credit Card Number'
                        },
                        cvv: {
                            selector: '#cvv',
                            placeholder: 'CVV'
                        },
                        expirationDate: {
                            selector: '#expiration-date',
                            placeholder: 'MM/YY'
                        },
                        styles: {
                            'input': {
                                'font-family': '"Helvetica Neue", Helvetica, Arial, sans-serif',
                                'font-size': '14px'
                            },
                            '::-moz-placeholder': {'color': '#999'},
                            ':-ms-input-placeholder': {'color': '#999'},
                            '::-webkit-input-placeholder': {'color': '#999'}
                        }
                    }
                });
            }
        });

        $('#secure-popover-text').popover({
            trigger: 'hover focus',
            content: 'All credit card information is processed by our external provider, BrainTree (a PayPal company), and fully encrypted every step of the way.',
            html: true,
            placement: 'right',
            container: 'body',
            delay: {
                'show': 100,
                'hide': 600
            }
        });
    });
}).on('click', '#seats-goback-button', function(e) {
    e.preventDefault();

    selectedSeats = [];
    selectedShow = null;

    getTemplate('/views/partials/showselection.ejs', function(err, template) {
        var showSelection = ejs.render(template);
        $('#content').html(showSelection);
        $('.breadcrumb li:eq(1)').toggleClass('active');
        initShows();
    });
}).on('click', '#checkout-goback-button', function(e) {
    e.preventDefault();

    selectedSeats = [];

    getTemplate('/views/partials/seatselection.ejs', function(err, template) {
        var seatSelection = ejs.render(template, {show: selectedShow, time: new Date(selectedShow.time)});
        $('#content').html(seatSelection);
        $('.breadcrumb li:eq(2)').toggleClass('active');
        initSeatCharts();
    });
}).on('click', '#student-info-button', function(e) {
    e.preventDefault();
});

function getTemplate(file, callback) {
    $.ajax(file, {
        type: 'GET',
        success: function(data, textStatus, xhr) {
            return callback(null, data);
        },
        error: function(xhr, textStatus, error) {
            return callback(error);
        }
    });
}

function initShows() {
    $.ajax({
        type: 'GET',
        url: '/api/v1/shows',
        dataType: 'JSON',
        success: function(data) {
            var showSelectionContainer = $('#show-selection-container');

            $('.spinner').remove();
            showSelectionContainer.removeClass('hidden');

            var html = '';
            data.forEach(function(show) {
                var time = new Date(show.time);
                html += '

' +
                    show.name + '

' + (time.getMonth() + 1) + '/'
                    + time.getDate() + '/'
                    + time.getFullYear() + ' '
                    + ((time.getHours() + 24) % 12 || 12) + ':'
                    + ('0' + time.getMinutes()).slice(-2)
                    + ((time.getHours() >= 12) ? 'PM' : 'AM') + '

';
            });
            showSelectionContainer.html(html);
        }
    });
}

function initSeatCharts() {
    $('#student-info-button').popover({
        trigger: 'hover focus',
        content: 'Anyone currently enrolled in school is a student. Children ages 5 and under are free.',
        placement: 'right',
        container: 'body',
        delay: {
            'show': 100,
            'hide': 600
        }
    });

    $.ajax({
        type: 'GET',
        url: '/api/v1/shows/' + selectedShow.id + '/purchased_seats',
        dataType: 'JSON',
        success: function(seats) {
            var seatMap = $('#seat-map');

            $('.spinner').remove();
            seatMap.removeClass('hidden');

            var seatChart = seatMap.seatCharts({
                map: [
                    '__aaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaa__',
                    'aaaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaaa',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '_aaaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaaa_',
                    '__aaaaaaaaaaaaaaaaa_aaaaaaaaaaaaaaaaa__'
                ],
                naming: {
                    columns: ['37', '35', '33', '31', '29', '27', '25', '23', '21', '19', '17', '15', '13', '11', '9', '7', '5', '3', '1', '', '2', '4', '6', '8', '10', '12', '14', '16', '18', '20', '22', '24', '26', '28', '30', '32', '34', '36', '38'],
                    rows: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
                },
                seats: {
                    a: {
                        classes: 'general'
                    }
                },
                click: function() {
                    if (this.status() === 'available' && selectedSeats.length < (parseInt($('#adultTickets').val()) + parseInt($('#studentTickets').val()))) {
                        // Add to array
                        selectedSeats.push(this.node()[0].id);
                        // Update counter
                        $('#seat-number').text(selectedSeats.length);
                        // Update status
                        return 'selected';
                    } else if (this.status() === 'selected') {
                        // Remove from array
                        selectedSeats.splice(selectedSeats.indexOf(this.node()[0].id), 1);
                        // Update counter
                        $('#seat-number').text(selectedSeats.length);
                        // Update status
                        return 'available';
                    } else if (this.status() === 'unavailable') {
                        return 'unavailable';
                    } else {
                        return this.style();
                    }
                }
            });

            seatChart.get(seats).status('unavailable');
        }
    });
}<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class RNDemo extends Component {
  render() {
    return (
      <View style={{flex: 1,flexDirection: 'column',justifyContent: 'center',alignItems: 'stretch'}}>
        <View style={{height:50,backgroundColor: 'powderblue'}}></View>
        <View style={{height:50,backgroundColor: 'skyblue'}}></View>
        <View style={{height:50,backgroundColor: 'steelblue'}}></View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('RNDemo', () => RNDemo);
<commit_msg>TextInput RN<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput
} from 'react-native';

export default class RNDemo extends Component {
  constructor(props){
    super(props);
    this.state={text:''};
  }
  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput style={{height: 50}} placeholder="Type here"
        onChangeText={(text)=>{this.setState({text})}}/>
        <Text style={{fontSize: 42}}>{this.state.text}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('RNDemo', () => RNDemo);
<|endoftext|>


<commit_before>function PPSinglesEditController(player1TextId, player2TextId, player1RadioId, player2RadioId, tournament) {
  if (player1TextId == null || player2TextId == null || player1RadioId == null || player2RadioId == null) {
    throw new Error("PPSinglesEditController missing required parameter.");
  }

  this.superclass(tournament);

  this.player1TextId = player1TextId;
  this.player2TextId = player2TextId;
  this.player1RadioId = player1RadioId;
  this.player2RadioId = player2RadioId;

  var self = this;
  // Bind to html elements when document is loaded.
  PPUtils.bind("load", window, function () {self.bind();} );
}

// This must be in between the constructor definition and
// new method definitions in order for it to work.
PPUtils.extend (PPSinglesEditController, PPEditController);

PPSinglesEditController.prototype.bind = function () {
  var self = this;
  PPUtils.bind("keyup", $(this.player1TextId), function () {self.updatePlayer1(self.player1TextId);} );
  PPUtils.bind("keyup", $(this.player2TextId), function () {self.updatePlayer2(self.player2TextId);} );
  PPUtils.bind("click", $(this.player1RadioId), function () {self.setMatchWinner();} );
  PPUtils.bind("click", $(this.player2RadioId), function () {self.setMatchWinner();} );
}

PPSinglesEditController.prototype.setMatchWinner = function() {
  var selectedMatch = this.tournament.getSelectedMatch();

  if (selectedMatch == null ) {
    throw new Error("Unexpected state");
  }

  if ( $(this.player1RadioId).checked ) {
    selectedMatch.setWinner(PPMatch.player1);
  } else {
    selectedMatch.setWinner(PPMatch.player2);
  }

}<commit_msg>Use getSelectedMatch, fix spelling mistake for global var reference.<commit_after>function PPSinglesEditController(player1TextId, player2TextId, player1RadioId, player2RadioId, tournament) {
  if (player1TextId == null || player2TextId == null || player1RadioId == null || player2RadioId == null) {
    throw new Error("PPSinglesEditController missing required parameter.");
  }

  this.superclass(tournament);

  this.player1TextId = player1TextId;
  this.player2TextId = player2TextId;
  this.player1RadioId = player1RadioId;
  this.player2RadioId = player2RadioId;

  var self = this;
  // Bind to html elements when document is loaded.
  PPUtils.bind("load", window, function () {self.bind();} );
}

// This must be in between the constructor definition and
// new method definitions in order for it to work.
PPUtils.extend (PPSinglesEditController, PPEditController);

PPSinglesEditController.prototype.bind = function () {
  var self = this;
  PPUtils.bind("keyup", $(this.player1TextId), function () {self.updatePlayer1(self.player1TextId);} );
  PPUtils.bind("keyup", $(this.player2TextId), function () {self.updatePlayer2(self.player2TextId);} );
  PPUtils.bind("click", $(this.player1RadioId), function () {self.setMatchWinner();} );
  PPUtils.bind("click", $(this.player2RadioId), function () {self.setMatchWinner();} );
}

PPSinglesEditController.prototype.setMatchWinner = function() {
  var selectedMatch = this.getSelectedMatch();

  if ( $(this.player1RadioId).checked ) {
    selectedMatch.setWinner(PPMatch.Player1);
  } else {
    selectedMatch.setWinner(PPMatch.Player2);
  }

}<|endoftext|>


<commit_before>// Copyright 2010 Mike Brevoort http://mike.brevoort.com @mbrevoort
//
// v1.0 jquery-facebook-multi-friend-selector
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

(function($) {
    var JFMFS = function(element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            param: 'defaultValue'
        }, options || {});
        var lastSelected;  // used when shift-click is performed to know where to start from to select multiple elements

        // ----------+----------+----------+----------+----------+----------+----------+
        // Initialization of container
        // ----------+----------+----------+----------+----------+----------+----------+
        elem.html(
            "
" +
            "
" +
            "        Find Friends: <input type='text' id='jfmfs-friend-filter-text'/>" +
            "        All" +
            "        Selected (0)" +
            "
" +
            "

" +
            "
"
        );

        FB.api('/me/friends', function(response) {
            $.each(response.data, function(i, friend) {
                $("#jfmfs-friend-container").append("

" + friend.name + "

");
            });
            init();
        });

        // ----------+----------+----------+----------+----------+----------+----------+
        // Public functions
        // ----------+----------+----------+----------+----------+----------+----------+

        this.getSelectedIds = function() {
            var ids = [];
            $.each(elem.find(".jfmfs-friend.selected"), function(i, friend) {
                ids.push($(friend).attr("id"));
            });
            return ids;
        };

        // ----------+----------+----------+----------+----------+----------+----------+
        // Private functions
        // ----------+----------+----------+----------+----------+----------+----------+

        var init = function() {
            // handle when a friend is clicked for selection
            elem.find(".jfmfs-friend").live('click', function(event) {
                $(this).toggleClass("selected");
                $(this).removeClass("hover");

                // support shift-click operations to select multiple items at a time
                if( $(this).hasClass("selected")) {
                    if ( !lastSelected ) {
                        lastSelected = $(this);
                    }
                    else {
                        if( event.shiftKey ) {
                            var selIndex = $(this).index();
                            var lastIndex = lastSelected.index();
                            var end = Math.max(selIndex,lastIndex);
                            var start = Math.min(selIndex,lastIndex);
                            for(var i=start; i<=end; i++) {
                                var aFriend = $( $(".jfmfs-friend")[i] );
                                if(!aFriend.hasClass("hide-non-selected") && !aFriend.hasClass("hide-filtered"))
                                    $( $(".jfmfs-friend")[i] ).addClass("selected");
                            }
                        }
                    }
                }
                lastSelected = $(this);
                $("#jfmfs-selected-count").html($(".jfmfs-friend.selected").size());
            });

            // filter by selected, hide all non-selected
            elem.find("#jfmfs-filter-selected").live('click', function() {
                $(".jfmfs-friend").not(".selected").addClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // remove filter, show all
            elem.find("#jfmfs-filter-all").live('click', function() {
                $(".jfmfs-friend").removeClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // hover effect on friends
            elem.find(".jfmfs-friend:not(.selected)").live(
                'hover', function (ev) {
                    if (ev.type == 'mouseover') {
                        $(this).addClass("hover");
                    }
                    if (ev.type == 'mouseout') {
                        $(this).removeClass("hover");
                    }
                });

            // filter as you type
            elem.find("#jfmfs-friend-filter-text")
                .keyup( function() {
                    var filter = $(this).val();
                    if(filter == '') {
                        $(".jfmfs-friend").removeClass("hide-filtered");
                    }
                    else {
                        $("#jfmfs-friend-selector").find(".friend-name:not(:Contains(" + filter +"))").parent().addClass("hide-filtered");
                        $("#jfmfs-friend-selector").find(".friend-name:Contains(" + filter +")").parent().removeClass("hide-filtered");
                    }
                })
                .focus( function() {
                    if($.trim($(this).val()) == 'Start typing a name')
                        $(this).val('');
                    })
                .blur(function() {
                    if($.trim($(this).val()) == '')
                        $(this).val('Start typing a name');
                    });

            // hover states on the buttons
            elem.find(".jfmfs-button").hover(
                function(){ $(this).addClass("jfmfs-button-hover");} ,
                function(){ $(this).removeClass("jfmfs-button-hover");}
            );

        };

    };

    $.fn.jfmfs = function(options) {
        return this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('jfmfs')) return;

            // pass options to plugin constructor
            var jfmfs = new JFMFS(this, options);

            // Store plugin object in this element's data
            element.data('jfmfs', jfmfs);

        });
    };

    // todo, make this more ambiguous
    jQuery.expr[':'].Contains = function(a, i, m) {
      return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

})(jQuery);
<commit_msg>added max selected option<commit_after>// Copyright 2010 Mike Brevoort http://mike.brevoort.com @mbrevoort
//
// v1.0 jquery-facebook-multi-friend-selector
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

(function($) {
    var JFMFS = function(element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            max_selected: 25
        }, options || {});
        var lastSelected;  // used when shift-click is performed to know where to start from to select multiple elements

        // ----------+----------+----------+----------+----------+----------+----------+
        // Initialization of container
        // ----------+----------+----------+----------+----------+----------+----------+
        elem.html(
            "
" +
            "
" +
            "        Find Friends: <input type='text' id='jfmfs-friend-filter-text'/>" +
            "        All" +
            "        Selected (0)" +
            "
" +
            "

" +
            "
"
        );

        FB.api('/me/friends', function(response) {
            $.each(response.data, function(i, friend) {
                $("#jfmfs-friend-container").append("

" + friend.name + "

");
            });
            init();
        });

        // ----------+----------+----------+----------+----------+----------+----------+
        // Public functions
        // ----------+----------+----------+----------+----------+----------+----------+

        this.getSelectedIds = function() {
            var ids = [];
            $.each(elem.find(".jfmfs-friend.selected"), function(i, friend) {
                ids.push($(friend).attr("id"));
            });
            return ids;
        };

        // ----------+----------+----------+----------+----------+----------+----------+
        // Private functions
        // ----------+----------+----------+----------+----------+----------+----------+

        var init = function() {
            // handle when a friend is clicked for selection
            elem.find(".jfmfs-friend").live('click', function(event) {
                if(!$(this).hasClass("selected") && $(".jfmfs-friend.selected").size() >= settings.max_selected)
                    return;
                $(this).toggleClass("selected");
                $(this).removeClass("hover");

                // support shift-click operations to select multiple items at a time
                if( $(this).hasClass("selected")) {
                    if ( !lastSelected ) {
                        lastSelected = $(this);
                    }
                    else {
                        if( event.shiftKey ) {
                            var selIndex = $(this).index();
                            var lastIndex = lastSelected.index();
                            var end = Math.max(selIndex,lastIndex);
                            var start = Math.min(selIndex,lastIndex);
                            for(var i=start; i<=end; i++) {
                                var aFriend = $( $(".jfmfs-friend")[i] );
                                if(!aFriend.hasClass("hide-non-selected") && !aFriend.hasClass("hide-filtered"))
                                    if($(".jfmfs-friend.selected").size() < settings.max_selected)
                                        $( $(".jfmfs-friend")[i] ).addClass("selected");
                            }
                        }
                    }
                }
                lastSelected = $(this);
                $("#jfmfs-selected-count").html($(".jfmfs-friend.selected").size());
            });

            // filter by selected, hide all non-selected
            elem.find("#jfmfs-filter-selected").live('click', function() {
                $(".jfmfs-friend").not(".selected").addClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // remove filter, show all
            elem.find("#jfmfs-filter-all").live('click', function() {
                $(".jfmfs-friend").removeClass("hide-non-selected");
                $(".filter-link").removeClass("selected");
                $(this).addClass("selected");
            });

            // hover effect on friends
            elem.find(".jfmfs-friend:not(.selected)").live(
                'hover', function (ev) {
                    if (ev.type == 'mouseover') {
                        $(this).addClass("hover");
                    }
                    if (ev.type == 'mouseout') {
                        $(this).removeClass("hover");
                    }
                });

            // filter as you type
            elem.find("#jfmfs-friend-filter-text")
                .keyup( function() {
                    var filter = $(this).val();
                    if(filter == '') {
                        $(".jfmfs-friend").removeClass("hide-filtered");
                    }
                    else {
                        $("#jfmfs-friend-selector").find(".friend-name:not(:Contains(" + filter +"))").parent().addClass("hide-filtered");
                        $("#jfmfs-friend-selector").find(".friend-name:Contains(" + filter +")").parent().removeClass("hide-filtered");
                    }
                })
                .focus( function() {
                    if($.trim($(this).val()) == 'Start typing a name')
                        $(this).val('');
                    })
                .blur(function() {
                    if($.trim($(this).val()) == '')
                        $(this).val('Start typing a name');
                    });

            // hover states on the buttons
            elem.find(".jfmfs-button").hover(
                function(){ $(this).addClass("jfmfs-button-hover");} ,
                function(){ $(this).removeClass("jfmfs-button-hover");}
            );

        };

    };

    $.fn.jfmfs = function(options) {
        return this.each(function() {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('jfmfs')) return;

            // pass options to plugin constructor
            var jfmfs = new JFMFS(this, options);

            // Store plugin object in this element's data
            element.data('jfmfs', jfmfs);

        });
    };

    // todo, make this more ambiguous
    jQuery.expr[':'].Contains = function(a, i, m) {
      return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

})(jQuery);
<|endoftext|>


<commit_before>var locationHelper = (function () {
	/**
	 * CustomEvent polyfill
	 * @see https://developer.mozilla.org/ru/docs/Web/API/CustomEvent/CustomEvent
	 */
	var CustomEvent = window.CustomEvent;
	if (typeof CustomEvent !== 'function') {
		CustomEvent = function (event, params) {
			params = params || { bubbles: false, cancelable: false, detail: undefined };
			var evt = document.createEvent('CustomEvent');
			evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
			return evt;
		}
		CustomEvent.prototype = window.Event.prototype;
	}

	function LocationHelper() {
		var prevChange = null;

		this.trigger = function (type, detail) {
			document.dispatchEvent(new CustomEvent(type, {
				detail: detail,
				bubbles: true,
				cancelable: false,
			}));

			if (type == 'location-change') {
				// trigger relative sub-events:
				if (!prevChange || prevChange.parts.path != detail.parts.path) {
					this.trigger('location-change-path', {
						href: detail.href,
						parts: detail.parts,
						prevPath: prevChange ? prevChange.parts.path : null,
						path: detail.parts.path,
					});
				}
				if (!prevChange || prevChange.parts.search != detail.parts.search) {
					this.trigger('location-change-search', {
						href: detail.href,
						parts: detail.parts,
						prevSearch: prevChange ? prevChange.parts.search : null,
						search: detail.parts.search,
					});
				}
				if (!prevChange || prevChange.parts.hash != detail.parts.hash) {
					this.trigger('location-change-hash', {
						href: detail.href,
						parts: detail.parts,
						prevHash: prevChange ? prevChange.parts.hash : null,
						hash: detail.parts.hash,
					});
				}

				prevChange = JSON.parse(JSON.stringify({
					href: detail.href,
					parts: detail.parts,
				}));
			}
		};
	}

	LocationHelper.prototype.parseParams = function (s) {
		var res = {};
		s = s.split('&');
		var param;
		for (var i = 0; i < s.length; i++) {
			if (!s[i])
				continue;
			param = s[i].split('=', 2);
			LocationHelper.setValueByPath(res, param[0], param.length > 1 ? param[1] : true);
		}
		LocationHelper.walkObjectTree(res, function (value, key, parent) {
			if (typeof value != 'object')
				return value;
			var arr = LocationHelper.isArray(value);
			return arr || value;
		});
		return res;
	};

	LocationHelper.setValueByPath = function (o, path, value) {
		if (!(path instanceof Array)) {
			path = path.replace(/^([^\[]+)/, '[$1]');
			path = path.slice(1, -1).split('][');
		}
		if (typeof value == 'string')
			value = decodeURIComponent(value);

		var name = path.pop();
		var res = o;
		var dir = false;
		while (path.length > 0) {
			dir = decodeURIComponent(path.shift());

			if (dir === '') {
				if (o[dir] && !(o[dir] instanceof Array))
					o[dir] = [];
			}
			else if (typeof o[dir] != 'object' || !o[dir]) {
				o[dir] = {};
			}

			if (path.length) {
				o = o[dir];
			}
		}

		if (name === '') {
			if (dir !== false && !(o[dir] instanceof Array))
				o[dir] = [];
			if (dir !== false) {
				var v = o[dir];
				delete o[dir];
				o[dir] = v;
				o = o[dir];
			}
			o.push(value);
		}
		else {
			if (dir !== false)
				o = o[dir];
			delete o[name];
			o[name] = value;
		}

		return o;
	};

	LocationHelper.isArray = function (o) {
		if (o instanceof Array)
			return true;
		if (typeof o != 'object' || !o)
			return false;
		var re = /^\d+$/;
		var arr = [];
		for (var k in o) {
			if (k == 'length')
				continue;
			if (!re.test(k))
				return false;
			arr[k] = o[k];
		}
		return arr;
	};

	LocationHelper.walkObjectTree = function (o, cb) {
		if (typeof o != 'object' || !o)
			return o;
		for (var k in o) {
			o[k] = cb(o[k], k, o);
			if (typeof o == 'object' && o) {
				this.walkObjectTree(o[k], cb);
			}
		}
		return o;
	};

	var parseURLRegExp = /^(?:(https?|file|[a-z]+):\/\/(?:([^\/:]+)(?::(\d+))?|))?(\/[^?#]*)?(\/?[^#]*)?(#\S*)?/;

	LocationHelper.prototype.parseURL = function (url) {
		var res = parseURLRegExp.exec(url);
		if (!res)
			return false;
		res = {
			schema: res[1],
			protocol: res[1] && res[1] + ':' || res[1],
			host: res[2],
			port: res[3],
			path: res[4],
			search: res[5],
			hash: res[6],
		};

		return res;
	};

	LocationHelper.prototype.buildURL = function (parts, baseParts) {
		if (!parts.protocol || parts.schema)
			parts.protocol = parts.schema + ':';
		else if (parts.protocol || !parts.schema)
			parts.schema = parts.protocol.slice(0, -1);

		if (baseParts) {
			if (!parts.protocol || !parts.host || !parts.port) {
				parts.protocol = baseParts.protocol;
				parts.schema = baseParts.schema;
				parts.host = baseParts.host;
				parts.port = baseParts.port;
			}
			if (!parts.path) {
				parts.path = baseParts.path;
			}
			if (parts.hash) {
				var newHash = parts.hash.split('!', 2);
				if (newHash.length < 2)
					newHash[1] = '';
				newHash[0] = newHash[0].length > 1 ? newHash[0] : (baseParts.hash && baseParts.hash.split('!')[0] || '');
				if (typeof newHash[1] == 'undefined') {
					newHash[1] = baseParts.hash && baseParts.hash.split('!')[1] || '';
				}
				else if (newHash[1][0] == '&') {
					newHash[1] = newHash[1].substr(1).split('&');
					var currentHashParams = this.getHashParams();
					for (var i = 0; i < newHash[1].length; i++) {
						var s = newHash[1][i].split('=', 2);
						LocationHelper.setValueByPath(currentHashParams, s[0], s[1]);
					}
					newHash[1] = this.buildParams(currentHashParams);
				}
				if (!newHash[1])
					newHash = [ newHash[0] ];
				if (newHash[1] && !newHash[0])
					newHash[0] = '#';
				parts.hash = newHash[0] == '#' && !newHash[1] ? '' : newHash.join('!');
			}
		}

		var s = [
			parts.path || '',
			parts.search || '',
			parts.hash || '',
		];

		if (parts.protocol == 'file:') {
			s.unshift(parts.protocol + '//');
		}
		else if (parts.host && parts.protocol) {
			if (parts.port)
				s.unshift(':' + parts.port);
			s.unshift(parts.host);
			s.unshift(parts.protocol + '//');
		}

		return s.join('');
	};

	LocationHelper.prototype.buildParams = function (o, parent) {
		if (typeof o != 'object')
			return parent + '=' + encodeURIComponent(o);

		var s = [];
		if (o instanceof Array) {
			for (var i = 0; i < o.length; i++) {
				var v = o[i];
				var path = parent ? parent + '[]' : '[]';
				s.push(this.buildParams(v, path));
			}
		}
		else {
			for (var k in o) {
				var v = o[k];
				var path = parent ? parent + '[' + encodeURIComponent(k) + ']' : encodeURIComponent(k);
				s.push(this.buildParams(v, path));
			}
		}
		return s.join('&');
	};

	LocationHelper.prototype.getHref = function () {
		return document.location.href;
	};

	LocationHelper.prototype.getHash = function () {
		return document.location.hash;
	};

	LocationHelper.prototype.getSearch = function () {
		return document.location.search;
	};

	LocationHelper.prototype.getPath = function () {
		return document.location.pathname;
	};

	LocationHelper.prototype.getHashParams = function () {
		var s = this.getHash();
		return this.parseParams(s.split('!', 2)[1] || '');
	};

	LocationHelper.prototype.getSearchParams = function () {
		var s = this.getSearch();
		return this.parseParams(s.slice(1));
	};

	LocationHelper.prototype.setLocation = function (hrefOrParts, replace, originalEvent) {
		var parts = typeof hrefOrParts == 'object' ? hrefOrParts : this.parseURL(hrefOrParts);
		var curParts = this.parseURL(this.getHref());
		var href = this.buildURL(parts, curParts);

		history[replace ? 'replaceState' : 'pushState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	LocationHelper.prototype.reload = function (originalEvent) {
		var href = this.getHref();
		var parts = this.parseURL(href);

		history['replaceState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	var bindParams = false;

	LocationHelper.prototype.bind = function (_bindParams) {
		_bindParams = _bindParams || true;
		if (!history || !history.pushState)
			return this;

		if (bindParams) {
			bindParams = _bindParams;
			return this;
		}
		bindParams = _bindParams;

		this.setLocation(document.location.href, true);
		var _this = this;

		window.addEventListener('popstate', function (event) {
			if (!event.state || !event.state.href || !event.state.parts)
				return;
			_this.trigger('location-change', {
				href: event.state.href,
				parts: event.state.parts,
				originalEvent: event,
			});
		}, false);

		document.body.addEventListener('click', function (event) {
			var a = event.target;
			while (a && a.nodeName != 'A')
				a = a.parentElement;
			if (a && a.target == '_null') {
				event.preventDefault();
				return false;
			}
			if (!a || !a.href || (a.target || '_self') != '_self')
				return;

			var parts = _this.parseURL(a.href);
			if (!parts || !/^https?:/.test(parts.protocol))
				return;

			var curParts = _this.parseURL(_this.getHref());
			if (parts.host != curParts.host || parts.protocol != curParts.protocol || parts.port != curParts.port)
				return;

			if (bindParams !== true && bindParams.path && curParts.path != parts.path)
				return;
			if (bindParams !== true && bindParams.search && curParts.search != parts.search)
				return;
			if (bindParams !== true && bindParams.hash && curParts.hash != parts.hash)
				return;

			_this.setLocation(parts, false, event);

			event.preventDefault();
		}, false);

		return this;
	}

	return new LocationHelper();
})();
<commit_msg>LocationHelper: fix serializing of null/undefined values<commit_after>var locationHelper = (function () {
	/**
	 * CustomEvent polyfill
	 * @see https://developer.mozilla.org/ru/docs/Web/API/CustomEvent/CustomEvent
	 */
	var CustomEvent = window.CustomEvent;
	if (typeof CustomEvent !== 'function') {
		CustomEvent = function (event, params) {
			params = params || { bubbles: false, cancelable: false, detail: undefined };
			var evt = document.createEvent('CustomEvent');
			evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
			return evt;
		}
		CustomEvent.prototype = window.Event.prototype;
	}

	function LocationHelper() {
		var prevChange = null;

		this.trigger = function (type, detail) {
			document.dispatchEvent(new CustomEvent(type, {
				detail: detail,
				bubbles: true,
				cancelable: false,
			}));

			if (type == 'location-change') {
				// trigger relative sub-events:
				if (!prevChange || prevChange.parts.path != detail.parts.path) {
					this.trigger('location-change-path', {
						href: detail.href,
						parts: detail.parts,
						prevPath: prevChange ? prevChange.parts.path : null,
						path: detail.parts.path,
					});
				}
				if (!prevChange || prevChange.parts.search != detail.parts.search) {
					this.trigger('location-change-search', {
						href: detail.href,
						parts: detail.parts,
						prevSearch: prevChange ? prevChange.parts.search : null,
						search: detail.parts.search,
					});
				}
				if (!prevChange || prevChange.parts.hash != detail.parts.hash) {
					this.trigger('location-change-hash', {
						href: detail.href,
						parts: detail.parts,
						prevHash: prevChange ? prevChange.parts.hash : null,
						hash: detail.parts.hash,
					});
				}

				prevChange = JSON.parse(JSON.stringify({
					href: detail.href,
					parts: detail.parts,
				}));
			}
		};
	}

	LocationHelper.prototype.parseParams = function (s) {
		var res = {};
		s = s.split('&');
		var param;
		for (var i = 0; i < s.length; i++) {
			if (!s[i])
				continue;
			param = s[i].split('=', 2);
			LocationHelper.setValueByPath(res, param[0], param.length > 1 ? param[1] : true);
		}
		LocationHelper.walkObjectTree(res, function (value, key, parent) {
			if (typeof value != 'object')
				return value;
			var arr = LocationHelper.isArray(value);
			return arr || value;
		});
		return res;
	};

	LocationHelper.setValueByPath = function (o, path, value) {
		if (!(path instanceof Array)) {
			path = path.replace(/^([^\[]+)/, '[$1]');
			path = path.slice(1, -1).split('][');
		}
		if (typeof value == 'string')
			value = decodeURIComponent(value);

		var name = path.pop();
		var res = o;
		var dir = false;
		while (path.length > 0) {
			dir = decodeURIComponent(path.shift());

			if (dir === '') {
				if (o[dir] && !(o[dir] instanceof Array))
					o[dir] = [];
			}
			else if (typeof o[dir] != 'object' || !o[dir]) {
				o[dir] = {};
			}

			if (path.length) {
				o = o[dir];
			}
		}

		if (name === '') {
			if (dir !== false && !(o[dir] instanceof Array))
				o[dir] = [];
			if (dir !== false) {
				var v = o[dir];
				delete o[dir];
				o[dir] = v;
				o = o[dir];
			}
			o.push(value);
		}
		else {
			if (dir !== false)
				o = o[dir];
			delete o[name];
			o[name] = value;
		}

		return o;
	};

	LocationHelper.isArray = function (o) {
		if (o instanceof Array)
			return o;
		if (typeof o != 'object' || !o)
			return false;
		var re = /^\d+$/;
		var arr = [];
		for (var k in o) {
			if (k == 'length')
				continue;
			if (!re.test(k))
				return false;
			arr[k] = o[k];
		}
		return arr;
	};

	LocationHelper.walkObjectTree = function (o, cb) {
		if (typeof o != 'object' || !o)
			return o;
		for (var k in o) {
			o[k] = cb(o[k], k, o);
			if (typeof o == 'object' && o) {
				this.walkObjectTree(o[k], cb);
			}
		}
		return o;
	};

	var parseURLRegExp = /^(?:(https?|file|[a-z]+):\/\/(?:([^\/:]+)(?::(\d+))?|))?(\/[^?#]*)?(\/?[^#]*)?(#\S*)?/;

	LocationHelper.prototype.parseURL = function (url) {
		var res = parseURLRegExp.exec(url);
		if (!res)
			return false;
		res = {
			schema: res[1],
			protocol: res[1] && res[1] + ':' || res[1],
			host: res[2],
			port: res[3],
			path: res[4],
			search: res[5],
			hash: res[6],
		};

		return res;
	};

	LocationHelper.prototype.buildURL = function (parts, baseParts) {
		if (!parts.protocol || parts.schema)
			parts.protocol = parts.schema + ':';
		else if (parts.protocol || !parts.schema)
			parts.schema = parts.protocol.slice(0, -1);

		if (baseParts) {
			if (!parts.protocol || !parts.host || !parts.port) {
				parts.protocol = baseParts.protocol;
				parts.schema = baseParts.schema;
				parts.host = baseParts.host;
				parts.port = baseParts.port;
			}
			if (!parts.path) {
				parts.path = baseParts.path;
			}
			if (parts.hash) {
				var newHash = parts.hash.split('!', 2);
				if (newHash.length < 2)
					newHash[1] = '';
				newHash[0] = newHash[0].length > 1 ? newHash[0] : (baseParts.hash && baseParts.hash.split('!')[0] || '');
				if (typeof newHash[1] == 'undefined') {
					newHash[1] = baseParts.hash && baseParts.hash.split('!')[1] || '';
				}
				else if (newHash[1][0] == '&') {
					newHash[1] = newHash[1].substr(1).split('&');
					var currentHashParams = this.getHashParams();
					for (var i = 0; i < newHash[1].length; i++) {
						var s = newHash[1][i].split('=', 2);
						LocationHelper.setValueByPath(currentHashParams, s[0], s[1]);
					}
					newHash[1] = this.buildParams(currentHashParams);
				}
				if (!newHash[1])
					newHash = [ newHash[0] ];
				if (newHash[1] && !newHash[0])
					newHash[0] = '#';
				parts.hash = newHash[0] == '#' && !newHash[1] ? '' : newHash.join('!');
			}
		}

		var s = [
			parts.path || '',
			parts.search || '',
			parts.hash || '',
		];

		if (parts.protocol == 'file:') {
			s.unshift(parts.protocol + '//');
		}
		else if (parts.host && parts.protocol) {
			if (parts.port)
				s.unshift(':' + parts.port);
			s.unshift(parts.host);
			s.unshift(parts.protocol + '//');
		}

		return s.join('');
	};

	LocationHelper.prototype.buildParams = function (o, parent) {
		if (typeof o == 'undefined' || o === null)
			return '';
		if (typeof o != 'object')
			return parent + '=' + encodeURIComponent(o);

		var s = [];
		if (o instanceof Array) {
			var prevDefinedI = -1;
			for (var i = 0; i < o.length; i++) {
				var v = o[i];
				if (typeof v == 'undefined' || v === null)
					continue;
				var path = parent ? parent + '[' : '[';
				if (i - prevDefinedI > 1)
					path += i;
				path += ']';
				s.push(this.buildParams(v, path));
				prevDefinedI = i;
			}
		}
		else {
			for (var k in o) {
				var v = o[k];
				if (typeof v == 'undefined' || v === null)
					continue;
				var path = parent ? parent + '[' + encodeURIComponent(k) + ']' : encodeURIComponent(k);
				s.push(this.buildParams(v, path));
			}
		}
		return s.join('&');
	};

	LocationHelper.prototype.getHref = function () {
		return document.location.href;
	};

	LocationHelper.prototype.getHash = function () {
		return document.location.hash;
	};

	LocationHelper.prototype.getSearch = function () {
		return document.location.search;
	};

	LocationHelper.prototype.getPath = function () {
		return document.location.pathname;
	};

	LocationHelper.prototype.getHashParams = function () {
		var s = this.getHash();
		return this.parseParams(s.split('!', 2)[1] || '');
	};

	LocationHelper.prototype.getSearchParams = function () {
		var s = this.getSearch();
		return this.parseParams(s.slice(1));
	};

	LocationHelper.prototype.setLocation = function (hrefOrParts, replace, originalEvent) {
		var parts = typeof hrefOrParts == 'object' ? hrefOrParts : this.parseURL(hrefOrParts);
		var curParts = this.parseURL(this.getHref());
		var href = this.buildURL(parts, curParts);

		history[replace ? 'replaceState' : 'pushState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	LocationHelper.prototype.reload = function (originalEvent) {
		var href = this.getHref();
		var parts = this.parseURL(href);

		history['replaceState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	var bindParams = false;

	LocationHelper.prototype.bind = function (_bindParams) {
		_bindParams = _bindParams || true;
		if (!history || !history.pushState)
			return this;

		if (bindParams) {
			bindParams = _bindParams;
			return this;
		}
		bindParams = _bindParams;

		this.setLocation(document.location.href, true);
		var _this = this;

		window.addEventListener('popstate', function (event) {
			if (!event.state || !event.state.href || !event.state.parts)
				return;
			_this.trigger('location-change', {
				href: event.state.href,
				parts: event.state.parts,
				originalEvent: event,
			});
		}, false);

		document.body.addEventListener('click', function (event) {
			var a = event.target;
			while (a && a.nodeName != 'A')
				a = a.parentElement;
			if (a && a.target == '_null') {
				event.preventDefault();
				return false;
			}
			if (!a || !a.href || (a.target || '_self') != '_self')
				return;

			var parts = _this.parseURL(a.href);
			if (!parts || !/^https?:/.test(parts.protocol))
				return;

			var curParts = _this.parseURL(_this.getHref());
			if (parts.host != curParts.host || parts.protocol != curParts.protocol || parts.port != curParts.port)
				return;

			if (bindParams !== true && bindParams.path && curParts.path != parts.path)
				return;
			if (bindParams !== true && bindParams.search && curParts.search != parts.search)
				return;
			if (bindParams !== true && bindParams.hash && curParts.hash != parts.hash)
				return;

			_this.setLocation(parts, false, event);

			event.preventDefault();
		}, false);

		return this;
	}

	return new LocationHelper();
})();
<|endoftext|>


<commit_before>/**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Encoding: UTF-8
'use strict';

/**
* SEARCH MODULE
*/
angular.module('module.search',['module.i18n', 'module.cookies']);

angular.module('module.search').constant('MAX_SEARCH_RESULTS', 20);

/**
* CONFIG
*/
angular.module('module.search').config(function($stateProvider) {

  $stateProvider
  .state('app.search', {
    url:'/search',
    controller: 'SearchController',
    templateUrl: MODULES_PREFIX + '/search/search.tpl.html'
  });

  $stateProvider.state('app.search.keywords', {
    url:'/keywords=:keywords',
    views: {
      "context": {
        templateUrl: MODULES_PREFIX + '/search/search-context.tpl.html',
        controller: function($stateParams, $scope) {
          $scope.clearSearch();
          $scope.performKeywordSearch($stateParams.keywords);
          $scope.performTagSearch($stateParams.keywords);
        },
      },
      "context-info":{
        templateUrl: MODULES_PREFIX + '/search/search-context-info.tpl.html'
      },
      "breadcrumbs":{
        templateUrl: MODULES_PREFIX + '/search/search-breadcrumbs.tpl.html'
      }
    },
      controller: 'SearchController'
  });

  $stateProvider.state('app.search.tag', {
    url:'/tag=:tag',
    views: {
      "context": {
        templateUrl: MODULES_PREFIX + '/search/search-context.tpl.html',
        controller: function($stateParams, $scope) {
          $scope.clearSearch();
          $scope.performTagSearch($stateParams.tag);
          $scope.performKeywordSearch($stateParams.tag);
        },
      },
      "context-info":{
        templateUrl: MODULES_PREFIX + '/search/search-context-info.tpl.html'
      },
      "breadcrumbs":{
        templateUrl: MODULES_PREFIX + '/search/search-breadcrumbs.tpl.html'
      }
    }
  });

});

/**
* CONTROLLER
*/
angular.module('module.search').controller("SearchController", [
  '$scope', '$rootScope', '$http', '$location', '$state', 'UserService', 'i18nService', 'SearchToolbox', 'UriToolbox','$q', 'EntityModel', '$dialogs', 'EntityFetchService','MAX_SEARCH_RESULTS', 'ENTITY_TYPES',
  function($scope, $rootScope, $http, $location, $state, UserSrv, i18nService, SearchToolbox, UriToolbox, $q, EntityModel, $dialogs, EntityFetchService, MAX_SEARCH_RESULTS, ENTITY_TYPES) {

    $scope.entityTypes = ENTITY_TYPES;

    $scope.showContentSearchResults = false;
    $scope.expandContentResults = false;

    $scope.showTagSearchResults = false;
    $scope.expandTagResults = false;

    $scope.contentSearchResultsCount = 0;
    $scope.tagSearchResultsCount = 0;

    $scope.contentSearchResults = new Array();
    $scope.tagSearchResults = new Array();

  /**
  * TRANSLATION INJECTION
  */
  $scope.t = function(identifier){
    return i18nService.t(identifier);
  }

  /**
  * METHODS
  */
  $scope.searchAction = function(){

    if($scope.searchForm.$invalid){
      return;
    }

    //todo filter not allowed chars
    if($scope.searchString != undefined || $scope.searchString != ""){

      var keywords = Array();
      angular.forEach($scope.searchString.split(","), function(string, key){
        angular.forEach(string.replace(/^\s+|\s+$/g, '').split(" "), function(subString, key2){
          keywords.push(subString);
        });
      });

      keywords = SearchToolbox.plusSeparateStringArray(keywords);
      $state.transitionTo('app.search.keywords', {keywords: keywords});
    }
  };

  $scope.performKeywordSearch = function(keywordsPlusSeparated){

    $scope.searchString = SearchToolbox.explodePlusSeparatedStringIntoString(keywordsPlusSeparated);

    var keywordsArray = SearchToolbox.explodeByPlus(keywordsPlusSeparated);
    if(keywordsArray.length > 0)
    {
      $rootScope.activateLoadingIndicator();
      var promise = searchByFullText(keywordsArray);
      promise.finally(function(){
        $rootScope.deactivateLoadingIndicator();
        $scope.showContentSearchResults = true;
      });

      $scope.toggleContentSearchResults();
    }
  };

  $scope.performTagSearch = function(tagsPlusSeparated){

    $scope.searchString = SearchToolbox.explodePlusSeparatedStringIntoString(tagsPlusSeparated);

    var tagsArray = SearchToolbox.explodeByPlus(tagsPlusSeparated);
    if(tagsArray.length > 0)
    {
      $rootScope.activateLoadingIndicator();
      var promise = searchByTags(tagsArray);
      promise.finally(function(){
        $rootScope.deactivateLoadingIndicator();
        $scope.showTagSearchResults = true;
      });

      $scope.toggleTagSearchResults();
    }
  };

  $scope.transitionToHome = function(){
    $state.go('app.collection.content',{coll: "root"});
  }

  var searchByTags = function(tagsArray){
   var defer = $q.defer();

   new SSSearchWithTags(
    function(result){

      var entities = new Array()

      if(result.searchResults.length > 0){
        var entities = initEntitiesBySearchResult(result.searchResults);
        $scope.tagSearchResults = entities;
        $scope.tagSearchResultsCount = result.searchResults.length;
      }

      defer.resolve(entities);
      $rootScope.$apply();
    },
    function(error){ console.log(error); },
    UserSrv.getUser(),
    UserSrv.getKey(),
    jSGlobals.or,
    tagsArray,
    MAX_SEARCH_RESULTS
    );

   return defer.promise;
 };

 var searchByFullText = function(keywordsArray){
  var defer = $q.defer();

  new SSSearchWithSolr(
    function(result){

      var entities = new Array()

      if(result.searchResults.length > 0){
        var entities = initEntitiesBySearchResult(result.searchResults);
        $scope.contentSearchResults = entities;
        $scope.contentSearchResultsCount = result.searchResults.length;
      }

      defer.resolve(entities);
      $rootScope.$apply();
    },
    function(error){ console.log(error); },
    UserSrv.getUser(),
    UserSrv.getKey(),
    jSGlobals.or,
    keywordsArray
    );

  return defer.promise;
};

var initEntitiesBySearchResult = function(searchResult){

  var entities = new Array();

  angular.forEach(searchResult, function(value, key){
    var entity = new EntityModel();
    entity.init(value);
    entity.init({type: value.type});
    entity.init({uriPathnameHash: UriToolbox.extractUriHostPartWithoutProtocol(value.id)});
    entities.push(entity);
  });

  return entities;
};

  $scope.entityClickAction = function(entity){

    var promise = EntityFetchService.getEntityByUri(entity.entity, true, true, true);

    promise.then(
      function(entity){

        var dialog = $dialogs.entryDetail(entity, true);
      },
      function(error){
        console.log(error);
      }
      );

  };

$scope.toggleContentSearchResults = function(){
  if($scope.expandContentResults){

    $scope.expandContentResults = false;
  }else{

    $scope.expandContentResults = true;
  }
};

$scope.toggleTagSearchResults = function(){
  if($scope.expandTagResults){

    $scope.expandTagResults = false;
  }else{

    $scope.expandTagResults = true;
  }
};

 $scope.clearSearch = function(){
    $scope.showContentSearchResults = false;
    $scope.expandContentResults = false;

    $scope.showTagSearchResults = false;
    $scope.expandTagResults = false;

    $scope.contentSearchResultsCount = 0;
    $scope.tagSearchResultsCount = 0;

    $scope.contentSearchResults = new Array();
    $scope.tagSearchResults = new Array();
 };

}]);

<commit_msg>LL-564<commit_after>/**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Encoding: UTF-8
'use strict';

/**
* SEARCH MODULE
*/
angular.module('module.search',['module.i18n', 'module.cookies']);

angular.module('module.search').constant('MAX_SEARCH_RESULTS', 20);

/**
* CONFIG
*/
angular.module('module.search').config(function($stateProvider) {

  $stateProvider
  .state('app.search', {
    url:'/search',
    controller: 'SearchController',
    templateUrl: MODULES_PREFIX + '/search/search.tpl.html'
  });

  $stateProvider.state('app.search.keywords', {
    url:'/keywords=:keywords',
    views: {
      "context": {
        templateUrl: MODULES_PREFIX + '/search/search-context.tpl.html',
        controller: function($stateParams, $scope) {
          $scope.clearSearch();
          $scope.performKeywordSearch($stateParams.keywords);
          $scope.performTagSearch($stateParams.keywords);
        },
      },
      "context-info":{
        templateUrl: MODULES_PREFIX + '/search/search-context-info.tpl.html'
      },
      "breadcrumbs":{
        templateUrl: MODULES_PREFIX + '/search/search-breadcrumbs.tpl.html'
      }
    },
      controller: 'SearchController'
  });

  $stateProvider.state('app.search.tag', {
    url:'/tag=:tag',
    views: {
      "context": {
        templateUrl: MODULES_PREFIX + '/search/search-context.tpl.html',
        controller: function($stateParams, $scope) {
          $scope.clearSearch();
          $scope.performTagSearch($stateParams.tag);
          $scope.performKeywordSearch($stateParams.tag);
        },
      },
      "context-info":{
        templateUrl: MODULES_PREFIX + '/search/search-context-info.tpl.html'
      },
      "breadcrumbs":{
        templateUrl: MODULES_PREFIX + '/search/search-breadcrumbs.tpl.html'
      }
    }
  });

});

/**
* CONTROLLER
*/
angular.module('module.search').controller("SearchController", [
  '$scope', '$rootScope', '$http', '$location', '$state', 'UserService', 'i18nService', 'SearchToolbox', 'UriToolbox','$q', 'EntityModel', '$dialogs', 'EntityFetchService','MAX_SEARCH_RESULTS', 'ENTITY_TYPES',
  function($scope, $rootScope, $http, $location, $state, UserSrv, i18nService, SearchToolbox, UriToolbox, $q, EntityModel, $dialogs, EntityFetchService, MAX_SEARCH_RESULTS, ENTITY_TYPES) {

    $scope.entityTypes = ENTITY_TYPES;

    $scope.showContentSearchResults = false;
    $scope.expandContentResults = false;

    $scope.showTagSearchResults = false;
    $scope.expandTagResults = false;

    $scope.contentSearchResultsCount = 0;
    $scope.tagSearchResultsCount = 0;

    $scope.contentSearchResults = new Array();
    $scope.tagSearchResults = new Array();

  /**
  * TRANSLATION INJECTION
  */
  $scope.t = function(identifier){
    return i18nService.t(identifier);
  }

  /**
  * METHODS
  */
  $scope.searchAction = function(){

    if($scope.searchForm.$invalid){
      return;
    }

    //todo filter not allowed chars
    if($scope.searchString != undefined || $scope.searchString != ""){

      var keywords = Array();
      angular.forEach($scope.searchString.split(","), function(string, key){
        angular.forEach(string.replace(/^\s+|\s+$/g, '').split(" "), function(subString, key2){
          keywords.push(subString);
        });
      });

      keywords = SearchToolbox.plusSeparateStringArray(keywords);
      $state.transitionTo('app.search.keywords', {keywords: keywords});
    }
  };

  $scope.performKeywordSearch = function(keywordsPlusSeparated){

    $scope.searchString = SearchToolbox.explodePlusSeparatedStringIntoString(keywordsPlusSeparated);

    var keywordsArray = SearchToolbox.explodeByPlus(keywordsPlusSeparated);
    if(keywordsArray.length > 0)
    {
      $rootScope.activateLoadingIndicator();
      var promise = searchByFullText(keywordsArray);
      promise.finally(function(){
        $rootScope.deactivateLoadingIndicator();
        $scope.showContentSearchResults = true;
      });

      $scope.toggleContentSearchResults();
    }
  };

  $scope.performTagSearch = function(tagsPlusSeparated){

    $scope.searchString = SearchToolbox.explodePlusSeparatedStringIntoString(tagsPlusSeparated);

    var tagsArray = SearchToolbox.explodeByPlus(tagsPlusSeparated);
    if(tagsArray.length > 0)
    {
      $rootScope.activateLoadingIndicator();
      var promise = searchByTags(tagsArray);
      promise.finally(function(){
        $rootScope.deactivateLoadingIndicator();
        $scope.showTagSearchResults = true;
      });

      $scope.toggleTagSearchResults();
    }
  };

  $scope.transitionToHome = function(){
    $state.go('app.collection.content',{coll: "root"});
  }

  var searchByTags = function(tagsArray){
    var defer = $q.defer();

    new SSSearch(
      function(result){

        var entities = new Array()

      if(result.entities.length > 0){
        var entities = initEntitiesBySearchResult(result.entities);
        $scope.tagSearchResults = entities;
        $scope.tagSearchResultsCount = result.entities.length;
      }

      defer.resolve(entities);
      $rootScope.$apply();
    },
    function(error){ console.log(error); },
    UserSrv.getUser(),
    UserSrv.getKey(),
    null, //keywordsToSearchFor
    false, //includeTextualContent,
    null, //wordsToSearchFor,
    true, //includeTags,
    tagsArray, //tagsToSearchFor,
    false, //includeMIs,
    null, //misToSearchFor,
    false, //includeLabel,
    null, //labelsToSearchFor,
    false, //includeDescription,
    null, //descriptionsToSearchFor,
    null, //typesToSearchOnlyFor,
    false, //includeOnlySubEntities,
    null, //entitiesToSearchWithin,
    false, //extendToParents,
    false, //includeRecommendedResults,
    false); //provideEntries,

    return defer.promise;
  };

  var searchByFullText = function(keywordsArray){
    var defer = $q.defer();

    new SSSearch(
      function(result){

        var entities = new Array()

      if(result.entities.length > 0){
        var entities = initEntitiesBySearchResult(result.entities);
        $scope.contentSearchResults      = entities;
        $scope.contentSearchResultsCount = result.entities.length;
      }

      defer.resolve(entities);
      $rootScope.$apply();
    },
    function(error){ console.log(error); },
    UserSrv.getUser(),
    UserSrv.getKey(),
    null, //keywordsToSearchFor
    true, //includeTextualContent,
    keywordsArray, //wordsToSearchFor,
    false, //includeTags,
    null, //tagsToSearchFor,
    false, //includeMIs,
    null, //misToSearchFor,
    false, //includeLabel,
    null, //labelsToSearchFor,
    false, //includeDescription,
    null, //descriptionsToSearchFor,
    null, //typesToSearchOnlyFor,
    false, //includeOnlySubEntities,
    null, //entitiesToSearchWithin,
    false, //extendToParents,
    false, //includeRecommendedResults,
    false); //provideEntries,

    return defer.promise;
  };

var initEntitiesBySearchResult = function(searchResult){

  var entities = new Array();

  angular.forEach(searchResult, function(value, key){
    var entity = new EntityModel();
    entity.init(value);
    entity.init({type: value.type});
    entity.init({uriPathnameHash: UriToolbox.extractUriHostPartWithoutProtocol(value.id)});
    entities.push(entity);
  });

  return entities;
};

  $scope.entityClickAction = function(entity){

    var promise = EntityFetchService.getEntityByUri(entity.id, true, true, true);

    promise.then(
      function(entity){

        var dialog = $dialogs.entryDetail(entity, true);
      },
      function(error){
        console.log(error);
      }
      );

  };

$scope.toggleContentSearchResults = function(){
  if($scope.expandContentResults){

    $scope.expandContentResults = false;
  }else{

    $scope.expandContentResults = true;
  }
};

$scope.toggleTagSearchResults = function(){
  if($scope.expandTagResults){

    $scope.expandTagResults = false;
  }else{

    $scope.expandTagResults = true;
  }
};

 $scope.clearSearch = function(){
    $scope.showContentSearchResults = false;
    $scope.expandContentResults = false;

    $scope.showTagSearchResults = false;
    $scope.expandTagResults = false;

    $scope.contentSearchResultsCount = 0;
    $scope.tagSearchResultsCount = 0;

    $scope.contentSearchResults = new Array();
    $scope.tagSearchResults = new Array();
 };

}]);

<|endoftext|>