<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var wishlist_div = "#div_wishlist_div";
var selected_itemId = -1;
var selected_eventId = -1;
var wishlistAddItemPath = '/app_dev.php/wishlistnew';
var wishlistElement = '#wishlist';

function setupEvents()
{
    $('.confirmEvent').on('click', clickedEvent);
}

function validateWish(wish)
{
    var message = "";

    if(!wish)
    {
        return "The wish object is empty.";
    }

    var name = wish.name,
        price = wish.price,
        link = wish.link;

    // validate the required inputs
    if(name.length < 3)
    {
        message += "
Name";
    }

    if(price.length < 1 || !IsNumber(price) || (IsNumber(price) && parseInt(price) <= 0 ))
    {
        message += "
Price";
    }

    var url_regexp = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w\.-]*)*\/?$/;
    if(link.length <= 0 || !url_regexp.test(link))
    {
        message += "
Link";
    }

    return (message.length > 0)
                        ? "The following Wish properties were not set properly:
 " + message
                        : message;
}

function IsNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function submitTheNewWish(/* optional wish object param */wish)
{
    // if a pre-defined wish obj was passed in, use that
    if(wish == null) {
        var theName = $("#newWishName").val();
        var thePrice = $("#newWishPrice").val();
        var theLink = $("#newWishLink").val();
        var theQuantity = $("#newWishQuantity").val();
        var theNotes = $("#newWishNotes").val();
        var theIsPrivate = $("#isPrivate").attr('checked');

        wish = { name: escape(theName),
                 price: thePrice,
                 link: theLink,
                 quantity: theQuantity,
                 comment: theNotes,
                 isprivate: theIsPrivate
             };
    }

    var invalidWishMessage = validateWish(wish);

    if(invalidWishMessage.length > 0)
    {
        popupMessage('Uh Oh!', invalidWishMessage);
    }
    else
    {
        ajaxPageLoad(
            wishlistElement,                // jQuery wishlist element
            wishlistAddItemPath,            // Path to the backend controller for adding a wish
            wish,                           // Wish object
            onCompleteAddToWishlistEvent    // Handles events after adding a wish
        );
    }
}

function onCompleteAddToWishlistEvent(responseText, textStatus)
{
    switch(textStatus.toLowerCase())
    {
        case "notmodified":
            popupMessage('Oh!','This item is already on your list! To edit the item, access it from your wishlist.');
            break;
        case "success":
            setupWishlist();
            popupMessage('Yay!','The item has been added to your list!');
            break;
        default:
            popupMessage('Sorry!', 'The item could not be added.');
            location.reload();
            break;
    }
}

function setupWishlist()
{
    $(wishlist_div).accordion({
        collapsible: true,
        active: false
    });

    $(wishlist_div).keyup(function(e) {
        if(e.keyCode === 13 )
        {
            e.preventDefault();
            submitTheNewWish();
        }
    });

    $('#submitNewWish').click(function(e){
        e.preventDefault();
        submitTheNewWish();
    })

    $("h3 .ui-icon-close").click(function(){
        var itemToDelete = escape($(this).next().text());
        confirm("Are you sure you want to delete this wish?")
        .then(function (answer) {
            if(answer == 1)
            {
                $(wishlist_div).accordion( "option", "disabled", true);
                var itemObj = {name: itemToDelete};
                delFromWishlist(itemObj, setupWishlist);
            }
        });
    });

    $('.purchaseBtn').on('click', clickedItem);

    $('#confirmDialog').dialog(
        {
            autoOpen: false,
            position: 'center',
            modal: true,
            open: confirmDialogOpen,
            close: confirmDialogClose
        }
    );

    $('#giftDateInput').datepicker();
}

function clickedItem()
{
    selected_itemId = $(this).attr('id');
    getItemInfo(selected_itemId, function(itemInfo){
        openAddToShoppingListDialog(itemInfo);
    });
}

function parseEventId(idString)
{
    var split_str = idString.split('_');

    if(split_str.length != 2)
        return -1;  //Return an invalid event id if we couldn't parse

    return parseInt(split_str[1]);
}

function clearEventHighlights()
{
    $('.confirmEvent').css('background-color', '');
}

function highlightEvent(selected)
{
    selected.css('background-color', '#999999');
}

function unselectEvent()
{
    clearEventHighlights();
    selected_eventId = -1;
}

function selectEvent(selected)
{
    var eventId = parseEventId(selected.attr('id'));

    if(eventId < 0)
        return;

    selected_eventId = eventId;
    clearEventHighlights();
    highlightEvent(selected)
}

function isSelectedEvent(selected)
{
    var eventId = parseEventId(selected.attr('id'));

    if( eventId == selected_eventId )
    {
        return true;

    }

    return false;
}

function toggleSelectEvent(selected)
{
    if( isSelectedEvent(selected) )
    {
        unselectEvent();
    }
    else
    {
        selectEvent(selected);
    }
}

function clickedEvent()
{
    toggleSelectEvent($(this));
}

function getItemInfo(itemId, callBackFunc)
{
    $.ajax({
        type: 'POST',
        url: '/app_dev.php/ItemInfo',
        data: {id: itemId}
    }).success(function(data){
        if(data)
            callBackFunc(data);
    });
}

function confirmOK()
{
    var purchaseType = null;
    var purchaseDue = null;

    try
    {
        var giftDate = parseDate($('#giftDateInput').attr('value'));
    }catch(e)
    {
        giftDate = null;
    }

    try
    {
        if(selected_itemId <= 0)
        {
            throw('Item is invalid.')
        }

        if((selected_eventId > 0) && (giftDate == null)){
            purchaseType = 'Event';
            purchaseDue = selected_eventId;
        }
        else if((giftDate != null) && (selected_eventId < 0)){
            purchaseType = 'Date';
            purchaseDue = giftDate.toDateString();
        }

        if(purchaseType == null || purchaseDue == null)
        {
            throw 'Please select either an event or a date.';
        }

        item = {id: selected_itemId, purchaseData: purchaseDue, type: purchaseType};
        ajaxPost(item, '/app_dev.php/purchaseItem', onCompleteAddItemToShoppingList, item.id);
    }catch(e)
    {
        alert(e);
        return;
    }
}

function onCompleteAddItemToShoppingList(responseMessage, responseObj, itemId){
    $('h3[id=' + itemId + ']').addClass('purchased');
    $('#confirmDialog').dialog('close');

    // if an empty string was returned it means that no errors occurred.
    if(responseObj.responseText.length <= 0){
        popupMessage('Done!', 'The item was successfully added to your shopping list.',
            function(){
                location.reload();
            });
    }
    else { // display the error if any occurred
        popupMessage('Sorry!','
'+responseObj.responseText+'
');
    }
}

function confirmDialogOpen()
{
    //Give the confirm button focus.
    $('#confirmBtn').focus();

    //Set up purchase button
    $('#confirmBtn').click(confirmOK);
}

function populateDialogItemInfo(itemInfo)
{
    if( !itemInfo )
    {
        $('#confirmDialog').dialog('close');
        return;
    }

    var type = whatIsIt(itemInfo);

    if(type == "null" || type == "undefined")
    {
        return;
    }

    var item = (type == "String") ? JSON.parse(itemInfo) : itemInfo;

    $('#confirmName').html(item.name);
}

function confirmDialogClose()
{
    unselectEvent();
    $('#confirmBtn').unbind('click');
}

$(document).ready(function(){
    setupWishlist();
    setupEvents();
});

function onGrantItClickEvent() {
    // Ask them to confirm first
    confirm('Are you sure you want to add this item to your shopping list?')
    .then(function(answer){
        if(answer == 1)
        {
            // call the method that pops open the dialog for adding the item
            openAddToShoppingListDialog(getItemDialogObj());
        }
    })
}

function openAddToShoppingListDialog(item)
{
    populateDialogItemInfo(item);
    selected_itemId = item.id;
    $('#confirmDialog').dialog('open');
}

function getItemDialogObj()
{
    return {
         id: $('#itemDialog #itemId').text(),
         name: $('#itemDialog #name').html(),
         price: $('#itemDialog #price').html(),
         link: $($('#itemDialog #link').html()).attr('href'),
         quantity: $('#itemDialog #quantity').html(),
         comment: $('#itemDialog #notes').html(),
         isprivate: $('#itemDialog #private').html()
     };
}

function onWantItClickEvent() {
    var buttonPane = $('.ui-dialog-buttonpane');

    // Ask them to fill out the additional details first
    confirm('Do you want to edit these first?

 Quantity = 1
Privacy = Public
 Notes = "" ')
    .then(function (answer) {
        if(answer == 1) // The user wants to fill out the details
        {
            // Display the div with the form fields for the user to fill out
            $('#wishDetails').show();

            // Hide the Grant Wish button and Change the text of the Want It button to Continue
            buttonPane.find('button').hide();
            buttonPane.find('button:contains("Add Wish")').show();
        }
        else { // The user will just use the default values, continue adding the item
            continueAddingItemToWishlist();

            // Close the dialog
            $("#itemDialog").dialog('close');
        }
    });
}

function continueAddingItemToWishlist()
{
    var buttonPane = $('.ui-dialog-buttonpane');
    var itemObj = getItemDialogObj();

    submitTheNewWish(itemObj); // defined in wishlist.js

    // Hide the add wish button now that we are done adding it
    buttonPane.find('button').show();
    buttonPane.find('button:contains("Add Wish")').hide();
}<commit_msg>There was a bug that would not permit users to grant a wish to themselves from their own wishlist<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var wishlist_div = "#div_wishlist_div";
var selected_itemId = -1;
var selected_eventId = -1;
var wishlistAddItemPath = '/app_dev.php/wishlistnew';
var wishlistElement = '#wishlist';

function setupEvents()
{
    $('.confirmEvent').on('click', clickedEvent);
}

function validateWish(wish)
{
    var message = "";

    if(!wish)
    {
        return "The wish object is empty.";
    }

    var name = wish.name,
        price = wish.price,
        link = wish.link;

    // validate the required inputs
    if(name.length < 3)
    {
        message += "
Name";
    }

    if(price.length < 1 || !IsNumber(price) || (IsNumber(price) && parseInt(price) <= 0 ))
    {
        message += "
Price";
    }

    var url_regexp = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w\.-]*)*\/?$/;
    if(link.length <= 0 || !url_regexp.test(link))
    {
        message += "
Link";
    }

    return (message.length > 0)
                        ? "The following Wish properties were not set properly:
 " + message
                        : message;
}

function IsNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function submitTheNewWish(/* optional wish object param */wish)
{
    // if a pre-defined wish obj was passed in, use that
    if(wish == null) {
        var theName = $("#newWishName").val();
        var thePrice = $("#newWishPrice").val();
        var theLink = $("#newWishLink").val();
        var theQuantity = $("#newWishQuantity").val();
        var theNotes = $("#newWishNotes").val();
        var theIsPrivate = $("#isPrivate").attr('checked');

        wish = { name: escape(theName),
                 price: thePrice,
                 link: theLink,
                 quantity: theQuantity,
                 comment: theNotes,
                 isprivate: theIsPrivate
             };
    }

    var invalidWishMessage = validateWish(wish);

    if(invalidWishMessage.length > 0)
    {
        popupMessage('Uh Oh!', invalidWishMessage);
    }
    else
    {
        ajaxPageLoad(
            wishlistElement,                // jQuery wishlist element
            wishlistAddItemPath,            // Path to the backend controller for adding a wish
            wish,                           // Wish object
            onCompleteAddToWishlistEvent    // Handles events after adding a wish
        );
    }
}

function onCompleteAddToWishlistEvent(responseText, textStatus)
{
    switch(textStatus.toLowerCase())
    {
        case "notmodified":
            popupMessage('Oh!','This item is already on your list! To edit the item, access it from your wishlist.');
            break;
        case "success":
            setupWishlist();
            popupMessage('Yay!','The item has been added to your list!');
            break;
        default:
            popupMessage('Sorry!', 'The item could not be added.');
            location.reload();
            break;
    }
}

function setupWishlist()
{
    $(wishlist_div).accordion({
        collapsible: true,
        active: false
    });

    $(wishlist_div).keyup(function(e) {
        if(e.keyCode === 13 )
        {
            e.preventDefault();
            submitTheNewWish();
        }
    });

    $('#submitNewWish').click(function(e){
        e.preventDefault();
        submitTheNewWish();
    })

    $("h3 .ui-icon-close").click(function(){
        var itemToDelete = escape($(this).next().text());
        confirm("Are you sure you want to delete this wish?")
        .then(function (answer) {
            if(answer == 1)
            {
                $(wishlist_div).accordion( "option", "disabled", true);
                var itemObj = {name: itemToDelete};
                delFromWishlist(itemObj, setupWishlist);
            }
        });
    });

    $('.purchaseBtn').on('click', clickedItem);

    $('#confirmDialog').dialog(
        {
            autoOpen: false,
            position: 'center',
            modal: true,
            open: confirmDialogOpen,
            close: confirmDialogClose
        }
    );

    $('#giftDateInput').datepicker();
}

function clickedItem()
{ // LEFT OFF HERE: check why selected_itemId is overwritten later
    selected_itemId = $(this).attr('id');
    getItemInfo(selected_itemId, function(itemInfo){
        openAddToShoppingListDialog(itemInfo);
    });
}

function parseEventId(idString)
{
    var split_str = idString.split('_');

    if(split_str.length != 2)
        return -1;  //Return an invalid event id if we couldn't parse

    return parseInt(split_str[1]);
}

function clearEventHighlights()
{
    $('.confirmEvent').css('background-color', '');
}

function highlightEvent(selected)
{
    selected.css('background-color', '#999999');
}

function unselectEvent()
{
    clearEventHighlights();
    selected_eventId = -1;
}

function selectEvent(selected)
{
    var eventId = parseEventId(selected.attr('id'));

    if(eventId < 0)
        return;

    selected_eventId = eventId;
    clearEventHighlights();
    highlightEvent(selected)
}

function isSelectedEvent(selected)
{
    var eventId = parseEventId(selected.attr('id'));

    if( eventId == selected_eventId )
    {
        return true;

    }

    return false;
}

function toggleSelectEvent(selected)
{
    if( isSelectedEvent(selected) )
    {
        unselectEvent();
    }
    else
    {
        selectEvent(selected);
    }
}

function clickedEvent()
{
    toggleSelectEvent($(this));
}

function getItemInfo(itemId, callBackFunc)
{
    $.ajax({
        type: 'POST',
        url: '/app_dev.php/ItemInfo',
        data: {id: itemId}
    }).success(function(data){
        if(data)
            callBackFunc(data);
    });
}

function confirmOK()
{
    var purchaseType = null;
    var purchaseDue = null;

    try
    {
        var giftDate = parseDate($('#giftDateInput').attr('value'));
    }catch(e)
    {
        giftDate = null;
    }

    try
    {
        if(selected_itemId == null || selected_itemId <= 0)
        {
            throw('Item is invalid.')
        }

        if((selected_eventId > 0) && (giftDate == null)){
            purchaseType = 'Event';
            purchaseDue = selected_eventId;
        }
        else if((giftDate != null) && (selected_eventId < 0)){
            purchaseType = 'Date';
            purchaseDue = giftDate.toDateString();
        }

        if(purchaseType == null || purchaseDue == null)
        {
            throw 'Please select either an event or a date.';
        }

        item = {id: selected_itemId, purchaseData: purchaseDue, type: purchaseType};
        ajaxPost(item, '/app_dev.php/purchaseItem', onCompleteAddItemToShoppingList, item.id);
    }catch(e)
    {
        alert(e);
        return;
    }
}

function onCompleteAddItemToShoppingList(responseMessage, responseObj, itemId){
    $('h3[id=' + itemId + ']').addClass('purchased');
    $('#confirmDialog').dialog('close');

    // if an empty string was returned it means that no errors occurred.
    if(responseObj.responseText.length <= 0){
        popupMessage('Done!', 'The item was successfully added to your shopping list.',
            function(){
                location.reload();
            });
    }
    else { // display the error if any occurred
        popupMessage('Sorry!','
'+responseObj.responseText+'
');
    }
}

function confirmDialogOpen()
{
    //Give the confirm button focus.
    $('#confirmBtn').focus();

    //Set up purchase button
    $('#confirmBtn').click(confirmOK);
}

function populateDialogItemInfo(itemInfo)
{
    if( !itemInfo )
    {
        $('#confirmDialog').dialog('close');
        return;
    }

    var type = whatIsIt(itemInfo);

    if(type == "null" || type == "undefined")
    {
        return;
    }

    var item = (type == "String") ? JSON.parse(itemInfo) : itemInfo;

    $('#confirmName').html(item.name);
}

function confirmDialogClose()
{
    unselectEvent();
    $('#confirmBtn').unbind('click');
}

$(document).ready(function(){
    setupWishlist();
    setupEvents();
});

function onGrantItClickEvent() {
    // Ask them to confirm first
    confirm('Are you sure you want to add this item to your shopping list?')
    .then(function(answer){
        if(answer == 1)
        {
            // call the method that pops open the dialog for adding the item
            openAddToShoppingListDialog(getItemDialogObj());
        }
    })
}

function openAddToShoppingListDialog(item)
{
    populateDialogItemInfo(item);
    if(selected_itemId <= -1)
    {
        selected_itemId = item.id;
    }
    $('#confirmDialog').dialog('open');
}

function getItemDialogObj()
{
    return {
         id: $('#itemDialog #itemId').text(),
         name: $('#itemDialog #name').html(),
         price: $('#itemDialog #price').html(),
         link: $($('#itemDialog #link').html()).attr('href'),
         quantity: $('#itemDialog #quantity').html(),
         comment: $('#itemDialog #notes').html(),
         isprivate: $('#itemDialog #private').html()
     };
}

function onWantItClickEvent() {
    var buttonPane = $('.ui-dialog-buttonpane');

    // Ask them to fill out the additional details first
    confirm('Do you want to edit these first?

 Quantity = 1
Privacy = Public
 Notes = "" ')
    .then(function (answer) {
        if(answer == 1) // The user wants to fill out the details
        {
            // Display the div with the form fields for the user to fill out
            $('#wishDetails').show();

            // Hide the Grant Wish button and Change the text of the Want It button to Continue
            buttonPane.find('button').hide();
            buttonPane.find('button:contains("Add Wish")').show();
        }
        else { // The user will just use the default values, continue adding the item
            continueAddingItemToWishlist();

            // Close the dialog
            $("#itemDialog").dialog('close');
        }
    });
}

function continueAddingItemToWishlist()
{
    var buttonPane = $('.ui-dialog-buttonpane');
    var itemObj = getItemDialogObj();

    submitTheNewWish(itemObj); // defined in wishlist.js

    // Hide the add wish button now that we are done adding it
    buttonPane.find('button').show();
    buttonPane.find('button:contains("Add Wish")').hide();
}<|endoftext|>


<commit_before>//////////// inspired by ionicframework modal
var ngModal = angular.module('ngModal',[]);

ngModal.factory('ModalProvider',['$rootScope', '$compile','$timeout', '$http', '$q', function($rootScope, $compile,$timeout,$http,$q){
    var service = {};

    var status = {};

    var modals = {};

    var currentModal = null;

    function fetchTemplate(url,opts) {
        return $http.get(url,{cache: opts.cache})
            .then(function(res){
                return res.data && res.data.trim();
            });
    }
    function compile(template,opts) {
        var scope = opts.scope && opts.scope.$new() || $rootScope.$new(true);
        return $compile(template)(scope);
    }

    function Modal(url,opts){
        var self = this;

        self.url = url;
        self.opts = opts || {
            cache: true // cache template
        };

        fetchTemplate(url,self.opts).then(function(template){
            self.compiledTpl = compile(template,self.opts);
            if(opts.pre_append){
                service.setModal(self);
                //$contentWrapper.append(self.compiledTpl);
            }
            if(self.status === Modal.STATUS.PENDING){
                self.status = Modal.STATUS.RESOLVED;
                self.show();
            }
            self.status = Modal.STATUS.RESOLVED;
        });
        modals[url] = this;
    }

    /// status
    Modal.STATUS = {
        RESOLVED: 1,
        PENDING: 2
    };

    Modal.prototype.show = function(){
        if(this.status !== Modal.STATUS.RESOLVED){
            this.status = Modal.STATUS.PENDING;
            return;
        }
        if(currentModal !== this){
            service.setModal(this);
        }
        $backdrop.addClass('active');
    };
    Modal.prototype.hide = function(){
        $backdrop.removeClass('active');
    };

    var $backdrop = angular.element('
');
    var $contentWrapper = angular.element('
');
    $backdrop.append($contentWrapper);
    $backdrop.on('click',function(e){
        e.stopPropagation();
        $backdrop.removeClass('active');
    });
    $contentWrapper.on('click',function(e){
        e.stopPropagation();
    });
    document.body.appendChild($backdrop[0]);

    service.fromTemplateUrl = function(url,opts){
        //return modals[url] || new Modal(url,opts);
        return new Modal(url,opts);
    };

    service.setModal = function(modal){
        currentModal = modal;
        $contentWrapper.html('');
        $contentWrapper.append(modal.compiledTpl);
    };

    ///////
    ///for dev console inspect
    // service.modals = modals;
    // window.ModalProvider = service;

    return service;
}]);<commit_msg>v0.0.0<commit_after>//////////// inspired by ionicframework modal
var ngModal = angular.module('ngModal',[]);

ngModal.factory('ModalProvider',['$rootScope', '$compile','$timeout', '$http', '$q', function($rootScope, $compile,$timeout,$http,$q){
    var service = {};

    var status = {};

    // var modals = {};

    var currentModal = null;

    function fetchTemplate(url,opts) {
        return $http.get(url,{cache: opts.cache})
            .then(function(res){
                return res.data && res.data.trim();
            });
    }
    function compile(template,opts) {
        var scope = opts.scope && opts.scope.$new() || $rootScope.$new(true);
        return $compile(template)(scope);
    }

    function Modal(url,opts){
        var self = this;

        self.url = url;
        self.opts = opts || {
            cache: true // cache template
        };

        fetchTemplate(url,self.opts).then(function(template){
            self.compiledTpl = compile(template,self.opts);
            if(opts.pre_append){
                service.setModal(self);
                //$contentWrapper.append(self.compiledTpl);
            }
            if(self.status === Modal.STATUS.PENDING){
                self.status = Modal.STATUS.RESOLVED;
                self.show();
            }
            self.status = Modal.STATUS.RESOLVED;
        });
        modals[url] = this;
    }

    /// status
    Modal.STATUS = {
        RESOLVED: 1,
        PENDING: 2
    };

    Modal.prototype.show = function(){
        if(this.status !== Modal.STATUS.RESOLVED){
            this.status = Modal.STATUS.PENDING;
            return;
        }
        if(currentModal !== this){
            service.setModal(this);
        }
        $backdrop.addClass('active');
    };
    Modal.prototype.hide = function(){
        $backdrop.removeClass('active');
    };

    var $backdrop = angular.element('
');
    var $contentWrapper = angular.element('
');
    $backdrop.append($contentWrapper);
    $backdrop.on('click',function(e){
        e.stopPropagation();
        $backdrop.removeClass('active');
    });
    $contentWrapper.on('click',function(e){
        e.stopPropagation();
    });
    document.body.appendChild($backdrop[0]);

    service.fromTemplateUrl = function(url,opts){
        //return modals[url] || new Modal(url,opts);
        return new Modal(url,opts);
    };

    service.setModal = function(modal){
        currentModal = modal;
        $contentWrapper.html('');
        $contentWrapper.append(modal.compiledTpl);
    };

    ///////
    ///for dev console inspect
    // service.modals = modals;
    // window.ModalProvider = service;

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


<commit_before>var ngMeteorTemplate = angular.module('ngMeteor.template', []);

<commit_msg>Updated file structure<commit_after><|endoftext|>


<commit_before>import { ATTRIBUTES } from '../constants';
import {
  ADD_FIELD,
  REMOVE_FIELD,
  UPDATE_FIELD,
  CHANGE_PAGE,
} from '../actions/query';

function firstUnusedAttribute(state) {
  let firstUnused = '';

  ATTRIBUTES.forEach(a => {
    if (!firstUnused && state[a] === undefined) firstUnused = a;
  });

  return firstUnused;
}

export default function query(state = {}, action) {
  const copiedState = Object.assign({}, state);
  copiedState.fields = Object.assign({}, state.fields);
  const addedField = action.attribute || firstUnusedAttribute(state);
  let newState = {};

  switch (action.type) {
    case ADD_FIELD:
      if (addedField) {
        Object.assign(copiedState.fields, { [addedField]: '' });
        newState = copiedState;
      } else {
        newState = state;
      }

      return newState;

    case UPDATE_FIELD:
      Object.assign(copiedState.fields, { [addedField]: action.value });
      return copiedState;

    case REMOVE_FIELD:
      delete copiedState.fields[action.attribute];
      return copiedState;

    case CHANGE_PAGE:
      return Object.assign(copiedState, { page: action.page });

    default:
      return state;
  }
}
<commit_msg>fix adding and updating fields after query format change<commit_after>import { ATTRIBUTES } from '../constants';
import {
  ADD_FIELD,
  REMOVE_FIELD,
  UPDATE_FIELD,
  CHANGE_PAGE,
} from '../actions/query';

function firstUnusedAttribute(fields) {
  let firstUnused = '';

  ATTRIBUTES.forEach(a => {
    if (!firstUnused && fields[a] === undefined) firstUnused = a;
  });

  return firstUnused;
}

export default function query(state = {}, action) {
  const copiedState = Object.assign({}, state);
  copiedState.fields = Object.assign({}, state.fields);
  let addedField = '';
  let newState = {};

  switch (action.type) {
    case ADD_FIELD:
      addedField = action.attribute || firstUnusedAttribute(state.fields);
      if (addedField) {
        Object.assign(copiedState.fields, { [addedField]: '' });
        newState = copiedState;
      } else {
        newState = state;
      }

      return newState;

    case UPDATE_FIELD:
      addedField = action.attribute || firstUnusedAttribute(state.fields);
      Object.assign(copiedState.fields, { [addedField]: action.value });
      return copiedState;

    case REMOVE_FIELD:
      delete copiedState.fields[action.attribute];
      return copiedState;

    case CHANGE_PAGE:
      return Object.assign(copiedState, { page: action.page });

    default:
      return state;
  }
}
<|endoftext|>


<commit_before>define(["config",
        "app/app",
        "socket.io"], function(config, App, io) {
  "use strict";

  Ember.Application.initializer({
    name: 'pubsub',
    after: "store",

    initialize: function(container, application) {
      App.PubSubController = Ember.Object.extend({
        subscribedTo: {},

        disconnect: function(data) {
          this.reconnect()
        },

        init: function() {
          this._super()

          this.set('socket', io.connect(config.host + '/'))

          this.get('socket').on('newPost', this.newPost.bind(this))
          this.get('socket').on('updatePost', this.updatePost.bind(this))
          this.get('socket').on('destroyPost', this.destroyPost.bind(this))
          this.get('socket').on('hidePost', this.hidePost.bind(this))
          this.get('socket').on('unhidePost', this.unhidePost.bind(this))

          this.get('socket').on('newComment', this.newComment.bind(this))
          this.get('socket').on('updateComment', this.updateComment.bind(this))
          this.get('socket').on('destroyComment', this.destroyComment.bind(this))

          this.get('socket').on('newLike', this.newLike.bind(this))
          this.get('socket').on('removeLike', this.removeLike.bind(this))

          this.get('socket').on('disconnect', this.disconnect.bind(this))
        },

        monitor: function() {
          var channel = this.get('channel')
          if (channel.constructor === App.Timeline)
            this.subscribe('timeline', channel.get('id'))
          else if (channel.constructor === App.Post)
            this.subscribe('post', channel.get('id'))
          else if (channel.constructor === Ember.ArrayProxy) {
            channel.get('content').forEach(function(post) {
              this.subscribe('post', post.get('id'))
            }, this)}
        }.observes('channel.id', 'channel.content.length'),

        subscribe: function(channel, ids) {
          if (!ids) return

          var subscribedTo = {}
          var that = this
          if (!$.isArray(ids))
            ids = [ids]

          if (this.subscribedTo[channel]) {
            ids.forEach(function(id) {
              var indexOfThisId = that.subscribedTo[channel].indexOf(id)
              if (indexOfThisId == -1) {
                that.subscribedTo[channel].push(id)
              }
            })
          } else {
            this.subscribedTo[channel] = ids
          }

          subscribedTo[channel] = ids
          this.socket.emit('subscribe', subscribedTo)
        },

        unsubscribe: function(channel, ids) {
          var unsubscribedTo = {}
          var that = this

          if (channel && ids) {
            if (this.subscribedTo[channel]) {
              if (!$.isArray(ids)) {
                ids = [ids]
              }
              ids.forEach(function(id) {
                var indexOfThisId = that.subscribedTo[channel].indexOf(id)
                if (indexOfThisId != -1) {
                  unsubscribedTo[channel].push(id)
                  that.subscribedTo[channel].splice(indexOfThisId, 1)
                }
              })
            }
          } else if(channel && !ids) {
            unsubscribedTo[channel] = this.subscribedTo[channel]
          } else if (!channel) {
            unsubscribedTo = this.subscribedTo
          }

          this.subscribedTo = {}
          this.socket.emit('unsubscribe', unsubscribedTo)
        },

        reconnect: function() {
          var subscribedTo = this.get('subscribedTo')
          this.unsubscribe()
          this.get('socket').emit('subscribe', subscribedTo)
        },

        isFirstPage: function() {
          var pageStart = this.currentController().get('pageStart')
          return pageStart === 0 ||
            pageStart === undefined
        },

        currentController: function() {
          var currentHandlerInfos = container.lookup('router:main').router.currentHandlerInfos
          var controller = currentHandlerInfos[currentHandlerInfos.length - 1].handler.controller

          return controller
        },

        newPost: function(data) {
          if (!this.isFirstPage())
            return
        },

        updatePost: function(data) {
        },

        hidePost: function(data) {
        },

        unhidePost: function(data) {
        },

        destroyPost: function(data) {
        },

        newComment: function(data) {
          if (!this.isFirstPage())
            return

          if (!this.store.recordIsLoaded('comment', data.comments.id)) {
            var post = this.store.getById('post', data.comments.postId)

            this.store.pushPayload('comment', data)
            var comment = this.store.getById('comment', data.comments.id)

            post.get('comments').pushObject(comment)
          }
        },

        updateComment: function(data) {
          var commentId = data.comments.id

          if (this.store.recordIsLoaded('comment', commentId)) {
            var comment = this.store.getById('comment', commentId)
            comment.set('body', data.comments.body)
          }
        },

        destroyComment: function(data) {
          var comment = this.store.getById('comment', data.commentId)

          if (!comment.get('isDeleted')) {
            this.store.unloadRecord(comment)

            var post = this.store.getById('post', data.postId)
            comment = post.get('comments').findProperty('id', comment.get('id'))
            post.get('comments').removeObject(comment)
          }
        },

        newLike: function(data) {
        },

        removeLike: function(data) {
        }
      })
    }
  })
})
<commit_msg>Supports pubsub new comment event when post does not exist in timeline yet<commit_after>define(["config",
        "app/app",
        "socket.io"], function(config, App, io) {
  "use strict";

  Ember.Application.initializer({
    name: 'pubsub',
    after: "store",

    initialize: function(container, application) {
      App.PubSubController = Ember.Object.extend({
        subscribedTo: {},

        disconnect: function(data) {
          this.reconnect()
        },

        init: function() {
          this._super()

          this.set('socket', io.connect(config.host + '/'))

          this.get('socket').on('newPost', this.newPost.bind(this))
          this.get('socket').on('updatePost', this.updatePost.bind(this))
          this.get('socket').on('destroyPost', this.destroyPost.bind(this))
          this.get('socket').on('hidePost', this.hidePost.bind(this))
          this.get('socket').on('unhidePost', this.unhidePost.bind(this))

          this.get('socket').on('newComment', this.newComment.bind(this))
          this.get('socket').on('updateComment', this.updateComment.bind(this))
          this.get('socket').on('destroyComment', this.destroyComment.bind(this))

          this.get('socket').on('newLike', this.newLike.bind(this))
          this.get('socket').on('removeLike', this.removeLike.bind(this))

          this.get('socket').on('disconnect', this.disconnect.bind(this))
        },

        monitor: function() {
          var channel = this.get('channel')
          if (channel.constructor === App.Timeline)
            this.subscribe('timeline', channel.get('id'))
          else if (channel.constructor === App.Post)
            this.subscribe('post', channel.get('id'))
          else if (channel.constructor === Ember.ArrayProxy) {
            channel.get('content').forEach(function(post) {
              this.subscribe('post', post.get('id'))
            }, this)}
        }.observes('channel.id', 'channel.content.length'),

        subscribe: function(channel, ids) {
          if (!ids) return

          var subscribedTo = {}
          var that = this
          if (!$.isArray(ids))
            ids = [ids]

          if (this.subscribedTo[channel]) {
            ids.forEach(function(id) {
              var indexOfThisId = that.subscribedTo[channel].indexOf(id)
              if (indexOfThisId == -1) {
                that.subscribedTo[channel].push(id)
              }
            })
          } else {
            this.subscribedTo[channel] = ids
          }

          subscribedTo[channel] = ids
          this.socket.emit('subscribe', subscribedTo)
        },

        unsubscribe: function(channel, ids) {
          var unsubscribedTo = {}
          var that = this

          if (channel && ids) {
            if (this.subscribedTo[channel]) {
              if (!$.isArray(ids)) {
                ids = [ids]
              }
              ids.forEach(function(id) {
                var indexOfThisId = that.subscribedTo[channel].indexOf(id)
                if (indexOfThisId != -1) {
                  unsubscribedTo[channel].push(id)
                  that.subscribedTo[channel].splice(indexOfThisId, 1)
                }
              })
            }
          } else if(channel && !ids) {
            unsubscribedTo[channel] = this.subscribedTo[channel]
          } else if (!channel) {
            unsubscribedTo = this.subscribedTo
          }

          this.subscribedTo = {}
          this.socket.emit('unsubscribe', unsubscribedTo)
        },

        reconnect: function() {
          var subscribedTo = this.get('subscribedTo')
          this.unsubscribe()
          this.get('socket').emit('subscribe', subscribedTo)
        },

        isFirstPage: function() {
          var pageStart = this.currentController().get('pageStart')
          return pageStart === 0 ||
            pageStart === undefined
        },

        currentController: function() {
          var currentHandlerInfos = container.lookup('router:main').router.currentHandlerInfos
          var controller = currentHandlerInfos[currentHandlerInfos.length - 1].handler.controller

          return controller
        },

        newPost: function(data) {
          if (!this.isFirstPage())
            return
        },

        updatePost: function(data) {
        },

        hidePost: function(data) {
        },

        unhidePost: function(data) {
        },

        destroyPost: function(data) {
        },

        newComment: function(data) {
          var that = this

          if (!this.isFirstPage())
            return

          var post = this.store.getById('post', data.comments.postId)

          if (post) {
            if (!this.store.recordIsLoaded('comment', data.comments.id)) {
              this.store.pushPayload('comment', data)
              var comment = this.store.getById('comment', data.comments.id)

              post.get('comments').pushObject(comment)
            }
          } else {
            this.store.find('post', data.comments.postId)
              .then(function(post) {
                that.currentController().get('posts').addObject(post)
              })
          }
        },

        updateComment: function(data) {
          var commentId = data.comments.id

          if (this.store.recordIsLoaded('comment', commentId)) {
            var comment = this.store.getById('comment', commentId)
            comment.set('body', data.comments.body)
          }
        },

        destroyComment: function(data) {
          var comment = this.store.getById('comment', data.commentId)

          if (!comment.get('isDeleted')) {
            this.store.unloadRecord(comment)

            var post = this.store.getById('post', data.postId)
            comment = post.get('comments').findProperty('id', comment.get('id'))
            post.get('comments').removeObject(comment)
          }
        },

        newLike: function(data) {
        },

        removeLike: function(data) {
        }
      })
    }
  })
})
<|endoftext|>


<commit_before>define(["config",
        "app/app",
        "socket.io"], function(config, App, io) {
  "use strict";

  Ember.Application.initializer({
    name: 'pubsub',
    after: "store",

    initialize: function(container, application) {
      App.PubSubController = Ember.Object.extend({
        subscribedTo: {},

        disconnect: function(data) {
          this.reconnect()
        },

        init: function() {
          this._super()

          this.set('socket', io.connect(config.host + '/'))

          this.get('socket').on('post:new', this.newPost.bind(this))
          this.get('socket').on('post:update', this.updatePost.bind(this))
          this.get('socket').on('post:destroy', this.destroyPost.bind(this))
          this.get('socket').on('post:hide', this.hidePost.bind(this))
          this.get('socket').on('post:unhide', this.unhidePost.bind(this))

          this.get('socket').on('comment:new', this.newComment.bind(this))
          this.get('socket').on('comment:update', this.updateComment.bind(this))
          this.get('socket').on('comment:destroy', this.destroyComment.bind(this))

          this.get('socket').on('like:new', this.newLike.bind(this))
          this.get('socket').on('like:remove', this.removeLike.bind(this))

          this.get('socket').on('disconnect', this.disconnect.bind(this))
        },

        monitor: function() {
          var channel = this.get('channel')
          if (channel) {
            if (channel.constructor === App.Timeline)
              this.subscribe('timeline', channel.get('id'))
            else if (channel.constructor === App.Post)
              this.subscribe('post', channel.get('id'))
            else if (channel.constructor === Ember.ArrayProxy) {
              channel.get('content').forEach(function(post) {
                this.subscribe('post', post.get('id'))
              }, this)
            }
          }
        }.observes('channel', 'channel.id', 'channel.content.length'),

        subscribe: function(channel, ids) {
          if (!ids) return

          var subscribedTo = {}
          var that = this
          if (!$.isArray(ids))
            ids = [ids]

          if (this.subscribedTo[channel]) {
            ids.forEach(function(id) {
              var indexOfThisId = that.subscribedTo[channel].indexOf(id)
              if (indexOfThisId == -1) {
                that.subscribedTo[channel].push(id)
              }
            })
          } else {
            this.subscribedTo[channel] = ids
          }

          subscribedTo[channel] = ids
          this.socket.emit('subscribe', subscribedTo)
        },

        unsubscribe: function(channel, ids) {
          var unsubscribedTo = {}
          var that = this

          if (channel && ids) {
            if (this.subscribedTo[channel]) {
              if (!$.isArray(ids)) {
                ids = [ids]
              }
              ids.forEach(function(id) {
                var indexOfThisId = that.subscribedTo[channel].indexOf(id)
                if (indexOfThisId != -1) {
                  unsubscribedTo[channel].push(id)
                  that.subscribedTo[channel].splice(indexOfThisId, 1)
                }
              })
            }
          } else if(channel && !ids) {
            unsubscribedTo[channel] = this.subscribedTo[channel]
          } else if (!channel) {
            unsubscribedTo = this.subscribedTo
          }

          this.subscribedTo = {}
          this.set('channel', null)
          this.socket.emit('unsubscribe', unsubscribedTo)
        },

        reconnect: function() {
          var subscribedTo = this.get('subscribedTo')
          this.unsubscribe()
          this.get('socket').emit('subscribe', subscribedTo)
        },

        isFirstPage: function() {
          var offset = this.currentController().get('offset')
          return offset === 0 || offset === undefined
        },

        currentController: function() {
          var currentHandlerInfos = container.lookup('router:main').router.currentHandlerInfos
          var controller = currentHandlerInfos[currentHandlerInfos.length - 1].handler.controller

          return controller
        },

        newPost: function(data) {
          if (!this.isFirstPage())
            return

          var post = this.store.getById('post', data.posts.id)
          if (!post) {
            this.store.pushPayload('post', data)
            post = this.store.getById('post', data.posts.id)

            this.currentController().model.get('posts').unshiftObject(post)
          }
        },

        updatePost: function(data) {
          var post = this.store.getById('post', data.posts.id)
          if (post) {
            post.set('body', data.posts.body)
          }
        },

        destroyPost: function(data) {
          var post = this.store.getById('post', data.meta.postId)
          if (post) {
            var posts = this.currentController().get('posts')
            if (posts)
              posts.removeObject(post)
          }
        },

        hidePost: function(data) {
          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            post.set('isHidden', true)
          }
        },

        unhidePost: function(data) {
          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            post.set('isHidden', false)
          }
        },

        newComment: function(data) {
          if (!this.isFirstPage())
            return

          var that = this
          var post = this.store.getById('post', data.comments.postId)

          if (post) {
            if (!this.store.recordIsLoaded('comment', data.comments.id)) {
              this.store.pushPayload('comment', data)
              var comment = this.store.getById('comment', data.comments.id)
              comment.set('isRealtime', true)

              post.get('comments').pushObject(comment)
            }
          } else {
            this.store.find('post', data.comments.postId)
              .then(function(post) {
                that.currentController().get('posts').addObject(post)
              })
          }
        },

        updateComment: function(data) {
          var commentId = data.comments.id

          if (this.store.recordIsLoaded('comment', commentId)) {
            var comment = this.store.getById('comment', commentId)
            comment.set('body', data.comments.body)
          }
        },

        destroyComment: function(data) {
          var comment = this.store.getById('comment', data.commentId)

          if (!comment.get('isDeleted')) {
            this.store.unloadRecord(comment)

            var post = this.store.getById('post', data.postId)
            comment = post.get('comments').findProperty('id', comment.get('id'))
            post.get('comments').removeObject(comment)
          }
        },

        newLike: function(data) {
          if (!this.isFirstPage())
            return

          var that = this
          var userId = data.users.id

          if (!this.store.recordIsLoaded('user', userId)) {
            this.store.pushPayload('user', data)
          }

          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            var user = this.store.getById('user', userId)
            post.get('likes').addObject(user)
          } else {
            this.store.find('post', data.meta.postId)
              .then(function(post) {
                that.currentController().get('posts').addObject(post)
              })
          }
        },

        removeLike: function(data) {
          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            var user = post.get('likes').findProperty('id', data.meta.userId)
            post.get('likes').removeObject(user)
          }
        }
      })
    }
  })
})
<commit_msg>That's really weird, like pushPayload is an async method (no callback though) that takes some time to push a right model to the store. Fixes #458.<commit_after>define(["config",
        "app/app",
        "socket.io"], function(config, App, io) {
  "use strict";

  Ember.Application.initializer({
    name: 'pubsub',
    after: "store",

    initialize: function(container, application) {
      App.PubSubController = Ember.Object.extend({
        subscribedTo: {},

        disconnect: function(data) {
          this.reconnect()
        },

        init: function() {
          this._super()

          this.set('socket', io.connect(config.host + '/'))

          this.get('socket').on('post:new', this.newPost.bind(this))
          this.get('socket').on('post:update', this.updatePost.bind(this))
          this.get('socket').on('post:destroy', this.destroyPost.bind(this))
          this.get('socket').on('post:hide', this.hidePost.bind(this))
          this.get('socket').on('post:unhide', this.unhidePost.bind(this))

          this.get('socket').on('comment:new', this.newComment.bind(this))
          this.get('socket').on('comment:update', this.updateComment.bind(this))
          this.get('socket').on('comment:destroy', this.destroyComment.bind(this))

          this.get('socket').on('like:new', this.newLike.bind(this))
          this.get('socket').on('like:remove', this.removeLike.bind(this))

          this.get('socket').on('disconnect', this.disconnect.bind(this))
        },

        monitor: function() {
          var channel = this.get('channel')
          if (channel) {
            if (channel.constructor === App.Timeline)
              this.subscribe('timeline', channel.get('id'))
            else if (channel.constructor === App.Post)
              this.subscribe('post', channel.get('id'))
            else if (channel.constructor === Ember.ArrayProxy) {
              channel.get('content').forEach(function(post) {
                this.subscribe('post', post.get('id'))
              }, this)
            }
          }
        }.observes('channel', 'channel.id', 'channel.content.length'),

        subscribe: function(channel, ids) {
          if (!ids) return

          var subscribedTo = {}
          var that = this
          if (!$.isArray(ids))
            ids = [ids]

          if (this.subscribedTo[channel]) {
            ids.forEach(function(id) {
              var indexOfThisId = that.subscribedTo[channel].indexOf(id)
              if (indexOfThisId == -1) {
                that.subscribedTo[channel].push(id)
              }
            })
          } else {
            this.subscribedTo[channel] = ids
          }

          subscribedTo[channel] = ids
          this.socket.emit('subscribe', subscribedTo)
        },

        unsubscribe: function(channel, ids) {
          var unsubscribedTo = {}
          var that = this

          if (channel && ids) {
            if (this.subscribedTo[channel]) {
              if (!$.isArray(ids)) {
                ids = [ids]
              }
              ids.forEach(function(id) {
                var indexOfThisId = that.subscribedTo[channel].indexOf(id)
                if (indexOfThisId != -1) {
                  unsubscribedTo[channel].push(id)
                  that.subscribedTo[channel].splice(indexOfThisId, 1)
                }
              })
            }
          } else if(channel && !ids) {
            unsubscribedTo[channel] = this.subscribedTo[channel]
          } else if (!channel) {
            unsubscribedTo = this.subscribedTo
          }

          this.subscribedTo = {}
          this.set('channel', null)
          this.socket.emit('unsubscribe', unsubscribedTo)
        },

        reconnect: function() {
          var subscribedTo = this.get('subscribedTo')
          this.unsubscribe()
          this.get('socket').emit('subscribe', subscribedTo)
        },

        isFirstPage: function() {
          var offset = this.currentController().get('offset')
          return offset === 0 || offset === undefined
        },

        currentController: function() {
          var currentHandlerInfos = container.lookup('router:main').router.currentHandlerInfos
          var controller = currentHandlerInfos[currentHandlerInfos.length - 1].handler.controller

          return controller
        },

        newPost: function(data) {
          if (!this.isFirstPage())
            return

          var post = this.store.getById('post', data.posts.id)
          if (!post) {
            this.store.pushPayload('post', data)
            var that = this
            Ember.run.next(function() {
              post = that.store.getById('post', data.posts.id)

              that.currentController().model.get('posts').unshiftObject(post)
            })
          }
        },

        updatePost: function(data) {
          var post = this.store.getById('post', data.posts.id)
          if (post) {
            post.set('body', data.posts.body)
          }
        },

        destroyPost: function(data) {
          var post = this.store.getById('post', data.meta.postId)
          if (post) {
            var posts = this.currentController().get('posts')
            if (posts)
              posts.removeObject(post)
          }
        },

        hidePost: function(data) {
          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            post.set('isHidden', true)
          }
        },

        unhidePost: function(data) {
          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            post.set('isHidden', false)
          }
        },

        newComment: function(data) {
          if (!this.isFirstPage())
            return

          var that = this
          var post = this.store.getById('post', data.comments.postId)

          if (post) {
            if (!this.store.recordIsLoaded('comment', data.comments.id)) {
              this.store.pushPayload('comment', data)
              var comment = this.store.getById('comment', data.comments.id)
              comment.set('isRealtime', true)

              post.get('comments').pushObject(comment)
            }
          } else {
            this.store.find('post', data.comments.postId)
              .then(function(post) {
                that.currentController().get('posts').addObject(post)
              })
          }
        },

        updateComment: function(data) {
          var commentId = data.comments.id

          if (this.store.recordIsLoaded('comment', commentId)) {
            var comment = this.store.getById('comment', commentId)
            comment.set('body', data.comments.body)
          }
        },

        destroyComment: function(data) {
          var comment = this.store.getById('comment', data.commentId)

          if (!comment.get('isDeleted')) {
            this.store.unloadRecord(comment)

            var post = this.store.getById('post', data.postId)
            comment = post.get('comments').findProperty('id', comment.get('id'))
            post.get('comments').removeObject(comment)
          }
        },

        newLike: function(data) {
          if (!this.isFirstPage())
            return

          var that = this
          var userId = data.users.id

          if (!this.store.recordIsLoaded('user', userId)) {
            this.store.pushPayload('user', data)
          }

          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            var user = this.store.getById('user', userId)
            post.get('likes').addObject(user)
          } else {
            this.store.find('post', data.meta.postId)
              .then(function(post) {
                that.currentController().get('posts').addObject(post)
              })
          }
        },

        removeLike: function(data) {
          var post = this.store.getById('post', data.meta.postId)

          if (post) {
            var user = post.get('likes').findProperty('id', data.meta.userId)
            post.get('likes').removeObject(user)
          }
        }
      })
    }
  })
})
<|endoftext|>


<commit_before>//abstract base class
function InboxStateObject() {
    this.baseUrl = $("input[name='baseUrl']").val();
    this.currentUrl = window.location.pathname;
}

InboxStateObject.prototype.undo = function() {

    var me = this;
    $(document).delegate("a.undo", "click", function(e) {
        var feedid    = $(this).attr('href');
        var href      = $(this).attr('hrefaction');
        var undo_type = $(this).attr('undo-type');
        var undo_mode = $('.inbox-state').val();

        var current_catid = me.elem.attr('catid');
        var sec       = 350;

        $("#" + me.feeds.feedid).fadeIn(sec);
        $(this).parents("."+undo_type).fadeOut(sec, function() { $(this).remove(); });
        $.ajax({  type: "POST"
                , url: href
                , data: {"mode": undo_mode, "feed_ids": [me.feeds], "cat_id": current_catid, "catstate": true}
                , success: function () {
                    var myStatus = new Status();
                    myStatus.notify("Processing...", 1000);
                  }
               });
        e.preventDefault();
    });
}

InboxStateObject.prototype.process = function() {

    var me = this;
    var is_single = $(me).attr('feedid');
    var published_tab = me.currentUrl.match(/published|contacts/g);
    var mode = (me.state == 1) ? "inbox" : me.mode;
    var state_data = { "mode": mode, "feed_ids": [me.feeds], "cat_id": me.catid }
    var state_view_data;

    if(is_single) {
        if(published_tab) {
            console.log("In Published tab");
            //HTML view transforms
            if(mode == 'feature') {
                state_view_data = {
                    'elem': me.elem
                  , 'color': '#FFFFE0'
                  , 'position': '-60px -34px'
                  , 'sibling': '.check'
                };

                switch_to(state_view_data);
            }

            if(mode == 'publish') {
                state_view_data = {
                    'elem': me.elem
                  , 'color': '#FFFFFF'
                  , 'position': '0px -34px'
                  , 'sibling': '.feature'
                };

                switch_to(state_view_data);
            }

            if(mode == 'inbox' || mode == 'delete') {
                $(me.elem).parents('.feedback').fadeOut(350);
            }
            console.log(state_data);

            $.ajax({ type: "POST"
                   , url: me.href
                   , data: state_data
                   , success: function() {
                         checky.html(notify).show();
                         var myStatus = new Status();
                         myStatus.notify("Processing...", 1000);
                     }
            });
        } else {
            console.log("Not in Published tab");
            $(me.elem).parents('.feedback').fadeOut(350, function() {
                console.log("pwet");
            });
            console.log(state_data);
        }
    }

    //TODO: if in Published Folder do not animate else animate in Inbox Folder only.
    /*
    if(is_single) {
        $(me.elem).parents('.feedback').fadeOut(350, function() {
            var undo       = "  Undo";
            var close_checky = "  Close";
            var notify_msg = me.message + undo + close_checky;
            var notify     = $('
').addClass(me.identifier).html(notify_msg);
            var checky = $('.checky-bar');

            if(me.state == 0) {
                console.log(me.href);
                console.log(me.state);

                $.ajax({ type: "POST"
                       , url: me.href
                       , data: {"mode": me.mode ,"feed_ids": [me.feeds], "cat_id": me.catid }
                       , success: function() {
                             checky.html(notify).show();
                             var myStatus = new Status();
                             myStatus.notify("Processing...", 1000);
                         }
                });

            } else {
                //if state is 1 then we're going back to the inbox
                console.log(me.href);
                console.log(me.state);

                $.ajax({ type: "POST"
                      , url: me.href
                      , data: {"mode": "inbox" ,"feed_ids": [me.feeds], "cat_id": me.catid }
                      , success: function() {
                            checky.html("
Feedback has been sent to the " + "Inbox " + undo + close_checky + "
")
                            .show();

                            var myStatus = new Status();
                            myStatus.notify("Processing...", 1000);
                        }
                });

            }

        });
    }
    */

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    })

}

//child implementation classes
function PublishStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.message = "Feedback has been published and moved to " + "Published Folder";
    this.mode    = "publish";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}
PublishStateObject.prototype = new InboxStateObject();

function FeatureStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.message = "Feedback has been published and moved to " + "Featured Folder";
    this.mode    = "feature";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}
FeatureStateObject.prototype = new InboxStateObject();

function RemoveStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.message = "Feedback has been " + "deleted";
    this.mode    = "delete";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}
RemoveStateObject.prototype = new InboxStateObject();

function CatPickObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.catstate = $(elem).attr('cat-state');
    if(this.catstate == 'default') {
        this.message = "Feedback has been sent to " + "Inbox";
    } else {
        this.message = "Feedback has been sent to " + "Filed Feedback";
    }
    this.mode    = "fileas";
    $(elem).parents('div.category-picker-holder').hide();
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}

CatPickObject.prototype = new InboxStateObject();
CatPickObject.prototype.process = function() {
    var me = this;
    if(location.pathname.match(/filed|modifyfeedback/)) {
        $.ajax({ type: "POST", url: me.href, data: {"mode": me.mode ,"feed_ids": [me.feeds], "cat_id": me.catid, "catstate": me.catstate }, success: function() {
            if(me.catstate == "default") {
                $(me.elem).parents('.feedback').fadeOut(350);
            }
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        }});
    } else {
        $(this.elem).parents('.feedback').fadeOut(350, function() {
            var undo       = " Undo";
            var close_checky = "  Close";
            var notify_msg = me.message + undo + close_checky;
            var notify     = $('
').addClass(me.identifier).html(notify_msg);
            var checky = $('.checky-bar');

            if(me.state == 0) {
                $.ajax({ type: "POST", url: me.href, data: {"mode": me.mode ,"feed_ids": [me.feeds], "cat_id": me.catid, "catstate": me.catstate }, success: function()
                    {

                        var myStatus = new Status();
                        myStatus.notify("Processing...", 1000);
                        checky.html(notify).show();
                    }
                });
            } else {
                //if state is 1 then we're going back to the inbox
                $.ajax({ type: "POST", url: me.href, data: {"mode": "inbox" ,"feed_ids": [me.feeds], "cat_id": me.catid }, success: function()
                    {

                        var myStatus = new Status();
                        myStatus.notify("Processing...", 1000);
                        checky.html("
Feedback has been sent to the " + "Inbox " + undo + close_checky +"
")
                        .show();
                    }
                });
            }
        });

    }

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    })
}

//Factory
function InboxStatusChange(opts)  {
    this.inbox_controls = opts;
}

InboxStatusChange.prototype.initialize = function() {
    var me = this;
    $(document).delegate(me.inbox_controls, 'click', function(e) {
        var identifier = $(this).attr('class');
        var us = $(this);

        $.ajax({url: "/feedback/bust_hostfeed_data"});

        if(identifier == 'check') {
            var check = new PublishStateObject(us);
            check.process();
            check.undo();
        }

        if(identifier == 'feature') {
            var feature = new FeatureStateObject(us);
            feature.process();
            feature.undo();
        }

        if(identifier == 'remove' || identifier == 'popup-delete') {
            var remove = new RemoveStateObject(us);
            remove.process();
            remove.undo();
        }

    })
}

function switch_to(opts) {
    $(opts.elem).parents('.feedback').css({'background-color': opts.color});
    $(opts.elem).css({'background-position': opts.position});
    $(opts.elem).attr('state', 1);
    $(opts.elem).siblings(opts.sibling).removeAttr('style');
    $(opts.elem).siblings(opts.sibling).attr('state', 0);
}
<commit_msg>I let her succumb<commit_after>//abstract base class
function InboxStateObject() {
    this.baseUrl = $("input[name='baseUrl']").val();
    this.currentUrl = window.location.pathname;
}

InboxStateObject.prototype.undo = function() {

    var me = this;
    $(document).delegate("a.undo", "click", function(e) {
        var feedid    = $(this).attr('href');
        var href      = $(this).attr('hrefaction');
        var undo_type = $(this).attr('undo-type');
        var undo_mode = $('.inbox-state').val();

        var current_catid = me.elem.attr('catid');
        var sec       = 350;

        $("#" + me.feeds.feedid).fadeIn(sec);
        $(this).parents("."+undo_type).fadeOut(sec, function() { $(this).remove(); });
        $.ajax({  type: "POST"
                , url: href
                , data: {"mode": undo_mode, "feed_ids": [me.feeds], "cat_id": current_catid, "catstate": true}
                , success: function () {
                    var myStatus = new Status();
                    myStatus.notify("Processing...", 1000);
                  }
               });
        e.preventDefault();
    });
}

InboxStateObject.prototype.process = function() {

    var me = this;
    var is_single = $(me).attr('feedid');
    var published_tab = me.currentUrl.match(/published|contacts/g);
    var mode = (me.state == 1) ? "inbox" : me.mode;
    var state_data = { "mode": mode, "feed_ids": [me.feeds], "cat_id": me.catid }
    var state_view_data;

    if(is_single) {
        if(published_tab) {
            console.log("In Published tab");
            //HTML view transforms
            if(mode == 'feature') {
                state_view_data = {
                    'elem': me.elem
                  , 'color': '#FFFFE0'
                  , 'position': '-60px -34px'
                  , 'sibling': '.check'
                };

                switch_to(state_view_data);
            }

            if(mode == 'publish') {
                state_view_data = {
                    'elem': me.elem
                  , 'color': '#FFFFFF'
                  , 'position': '0px -34px'
                  , 'sibling': '.feature'
                };

                switch_to(state_view_data);
            }

            if(mode == 'inbox' || mode == 'delete') {
                $(me.elem).parents('.feedback').fadeOut(350);
            }

            console.log(state_data);

            $.ajax({ type: "POST"
                   , url: me.href
                   , data: state_data
                   , success: function() {
                         checky.html(notify).show();
                         var myStatus = new Status();
                         myStatus.notify("Processing...", 1000);
                     }
            });
        } else {
            console.log("Not in Published tab");
            $(me.elem).parents('.feedback').fadeOut(350, function() {
                console.log("pwet");
            });
            console.log(state_data);
        }
    }

    //TODO: if in Published Folder do not animate else animate in Inbox Folder only.
    /*
    if(is_single) {
        $(me.elem).parents('.feedback').fadeOut(350, function() {
            var undo       = "  Undo";
            var close_checky = "  Close";
            var notify_msg = me.message + undo + close_checky;
            var notify     = $('
').addClass(me.identifier).html(notify_msg);
            var checky = $('.checky-bar');

            if(me.state == 0) {
                console.log(me.href);
                console.log(me.state);

                $.ajax({ type: "POST"
                       , url: me.href
                       , data: {"mode": me.mode ,"feed_ids": [me.feeds], "cat_id": me.catid }
                       , success: function() {
                             checky.html(notify).show();
                             var myStatus = new Status();
                             myStatus.notify("Processing...", 1000);
                         }
                });

            } else {
                //if state is 1 then we're going back to the inbox
                console.log(me.href);
                console.log(me.state);

                $.ajax({ type: "POST"
                      , url: me.href
                      , data: {"mode": "inbox" ,"feed_ids": [me.feeds], "cat_id": me.catid }
                      , success: function() {
                            checky.html("
Feedback has been sent to the " + "Inbox " + undo + close_checky + "
")
                            .show();

                            var myStatus = new Status();
                            myStatus.notify("Processing...", 1000);
                        }
                });

            }

        });
    }
    */

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    })

}

//child implementation classes
function PublishStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.message = "Feedback has been published and moved to " + "Published Folder";
    this.mode    = "publish";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}
PublishStateObject.prototype = new InboxStateObject();

function FeatureStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.message = "Feedback has been published and moved to " + "Featured Folder";
    this.mode    = "feature";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}
FeatureStateObject.prototype = new InboxStateObject();

function RemoveStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.message = "Feedback has been " + "deleted";
    this.mode    = "delete";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}
RemoveStateObject.prototype = new InboxStateObject();

function CatPickObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.elem = elem;
    this.catstate = $(elem).attr('cat-state');
    if(this.catstate == 'default') {
        this.message = "Feedback has been sent to " + "Inbox";
    } else {
        this.message = "Feedback has been sent to " + "Filed Feedback";
    }
    this.mode    = "fileas";
    $(elem).parents('div.category-picker-holder').hide();
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}

CatPickObject.prototype = new InboxStateObject();
CatPickObject.prototype.process = function() {
    var me = this;
    if(location.pathname.match(/filed|modifyfeedback/)) {
        $.ajax({ type: "POST", url: me.href, data: {"mode": me.mode ,"feed_ids": [me.feeds], "cat_id": me.catid, "catstate": me.catstate }, success: function() {
            if(me.catstate == "default") {
                $(me.elem).parents('.feedback').fadeOut(350);
            }
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        }});
    } else {
        $(this.elem).parents('.feedback').fadeOut(350, function() {
            var undo       = " Undo";
            var close_checky = "  Close";
            var notify_msg = me.message + undo + close_checky;
            var notify     = $('
').addClass(me.identifier).html(notify_msg);
            var checky = $('.checky-bar');

            if(me.state == 0) {
                $.ajax({ type: "POST", url: me.href, data: {"mode": me.mode ,"feed_ids": [me.feeds], "cat_id": me.catid, "catstate": me.catstate }, success: function()
                    {

                        var myStatus = new Status();
                        myStatus.notify("Processing...", 1000);
                        checky.html(notify).show();
                    }
                });
            } else {
                //if state is 1 then we're going back to the inbox
                $.ajax({ type: "POST", url: me.href, data: {"mode": "inbox" ,"feed_ids": [me.feeds], "cat_id": me.catid }, success: function()
                    {

                        var myStatus = new Status();
                        myStatus.notify("Processing...", 1000);
                        checky.html("
Feedback has been sent to the " + "Inbox " + undo + close_checky +"
")
                        .show();
                    }
                });
            }
        });

    }

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    })
}

//Factory
function InboxStatusChange(opts)  {
    this.inbox_controls = opts;
}

InboxStatusChange.prototype.initialize = function() {
    var me = this;
    $(document).delegate(me.inbox_controls, 'click', function(e) {
        var identifier = $(this).attr('class');
        var us = $(this);

        $.ajax({url: "/feedback/bust_hostfeed_data"});

        if(identifier == 'check') {
            var check = new PublishStateObject(us);
            check.process();
            check.undo();
        }

        if(identifier == 'feature') {
            var feature = new FeatureStateObject(us);
            feature.process();
            feature.undo();
        }

        if(identifier == 'remove' || identifier == 'popup-delete') {
            var remove = new RemoveStateObject(us);
            remove.process();
            remove.undo();
        }

    })
}

function switch_to(opts) {
    $(opts.elem).parents('.feedback').css({'background-color': opts.color});
    $(opts.elem).css({'background-position': opts.position});
    $(opts.elem).attr('state', 1);
    $(opts.elem).siblings(opts.sibling).removeAttr('style');
    $(opts.elem).siblings(opts.sibling).attr('state', 0);
}
<|endoftext|>


<commit_before>(() => {
	'use strict';

	const http = require('http');
	const https = require('https');
	const { parse: urlParse } = require('url');

	const USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36'
	+ ' (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36';

	loadScripts();

	function loadScripts() {
		// Skip loading if already loaded
		if (window.better_emojis && window.better_emojis.loaded) {
			return;
		}

		window.better_emojis = {};

		getContent(
			'https://api.github.com/repos/TrueLecter/BetterDiscordEmojis/git/refs/heads/master'
		)
		.then(JSON.parse)
		.then(({ object: { sha: commitId } }) => (
			Promise.all([
				getRawGithub(
					`TrueLecter/BetterDiscordEmojis/${commitId}/jquery.js`
				),
				getRawGithub(
					`TrueLecter/BetterDiscordEmojis/${commitId}/better-emojis.js`
				)
			])
		))
		.then(([jQuery, betterEmojis]) => {
			if (!window.better_emojis.jquery) {
				addScript(jQuery);

				window.better_emojis.jquery = true;
			}

			if (!window.better_emojis.be) {
				addScript(betterEmojis);

				window.better_emojis.be = true;
			}

			window.better_emojis.loaded = true;

			console.log('Better-emojis scripts loaded');
		})
		.catch((error) => {
			console.log('Loaded scripts error', err);
			console.log('Retrying in 5 seconds...');

			setTimeout(loadScripts, 5000);
		});
	}

	/**
	 * Adds js at document
	 *
	 * @param {string} js
	 */
	function addScript(js) {
		const script = document.createElement('script');

		script.innerHTML = js;

		document.head.appendChild(script);
	}

	/**
	 * Returns github raw files
	 *
	 * @param {string} path
	 *
	 * @return {Promise<string>}
	 */
	function getRawGithub(path) {
		path = 'https://raw.githubusercontent.com/' + path;

		return getContent(path);
	}

	/**
	 * Fetch content with HTTP
	 *
	 * @param {string}  url
	 *
	 * @return {Promise<string>}
	 */
	function getContent(url) {
		return new Promise((resolve, reject) => {
			const { path, hostname, protocol } = urlParse(url);

			const resolver = protocol === 'https:' ? https : http;

			const options = {
				path,
				hostname,
				headers: {
					'User-Agent': USER_AGENT
				}
			};

			resolver(options, (response) => {
				if (response.statusCode < 200 || response.statusCode > 299) {
					return reject(
						new Error(`Failed to load page, status code: ${response.statusCode}`)
					);
				}

				let body = '';

				response
				.on('data', () => body += chunk)
				.on('end', () => resolve(body));

			})
			.on('error', reject);
		});
	}
})();
<commit_msg>Fixed some minor errors<commit_after>(() => {
	'use strict';

	const http = require('http');
	const https = require('https');
	const { parse: urlParse } = require('url');

	const USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36'
	+ ' (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36';

	loadScripts();

	function loadScripts() {
		// Skip loading if already loaded
		if (window.better_emojis && window.better_emojis.loaded) {
			return;
		}

		window.better_emojis = {};

		getContent(
			'https://api.github.com/repos/TrueLecter/BetterDiscordEmojis/git/refs/heads/master'
		)
		.then(JSON.parse)
		.then(({ object: { sha: commitId } }) => (
			Promise.all([
				getRawGithub(
					`TrueLecter/BetterDiscordEmojis/${commitId}/jquery.js`
				),
				getRawGithub(
					`TrueLecter/BetterDiscordEmojis/${commitId}/better-emojis.js`
				)
			])
		))
		.then(([jQuery, betterEmojis]) => {
			if (!window.better_emojis.jquery) {
				addScript(jQuery);

				window.better_emojis.jquery = true;
			}

			if (!window.better_emojis.be) {
				addScript(betterEmojis);

				window.better_emojis.be = true;
			}

			window.better_emojis.loaded = true;

			console.log('Better-emojis scripts loaded');
		})
		.catch((error) => {
			console.log('Loaded scripts error', error);
			console.log('Retrying in 5 seconds...');

			setTimeout(loadScripts, 5000);
		});
	}

	/**
	 * Adds js at document
	 *
	 * @param {string} js
	 */
	function addScript(js) {
		const script = document.createElement('script');

		script.innerHTML = js;

		document.head.appendChild(script);
	}

	/**
	 * Returns github raw files
	 *
	 * @param {string} path
	 *
	 * @return {Promise<string>}
	 */
	function getRawGithub(path) {
		path = 'https://raw.githubusercontent.com/' + path;

		return getContent(path);
	}

	/**
	 * Fetch content with HTTP
	 *
	 * @param {string}  url
	 *
	 * @return {Promise<string>}
	 */
	function getContent(url) {
		return new Promise((resolve, reject) => {
			const { path, hostname, protocol } = urlParse(url);

			const resolver = protocol === 'https:' ? https : http;

			const options = {
				path,
				hostname,
				headers: {
					'User-Agent': USER_AGENT
				}
			};

			resolver.get(options, (response) => {
				if (response.statusCode < 200 || response.statusCode > 299) {
					return reject(
						new Error(`Failed to load page, status code: ${response.statusCode}`)
					);
				}

				let body = '';

				response
				.on('data', (chunk) => body += chunk)
				.on('end', () => resolve(body));

			})
			.on('error', reject);
		});
	}
})();
<|endoftext|>


<commit_before>/**
 * 	@author       Rémi MARTIN <martinremi60@gmail.com>
 * 	@copyright    2014 Rémi MARTIN
 */

/**
 * 	Creates a new GraphicPolyline object.
 * 	The GraphicPolyline is defined with a polyline and some colors.
 * 	@class GraphicPolyline
 * 	@classdesc yom - GraphicPolyline
 * 	@constructor
 * 	@param {yom.Polyline} [polyline] - The polyline to copy
 * 	@param {number} [zIndex] - The zIndex of the polyline
 * 	@param {String} [borderColor] - The border color for the polyline
 *	@param {number} [lineWidth=1] - The border width (optionnal 1 is by default)
 * 	@param {String} [insideColor] - The inside color for the polyline
 * 	@return {yom.GrapphicPolyline} The GraphicPolyline object
 *
 *	TODO : Add color
 */
yom.GraphicPolyline = function (polyline, zIndex, borderColor, lineWidth, insideColor) {

	/**
     * 	@property {yom.Polyline} polyline - The polyline we want to display
     */
	this.polyline = polyline || {};

	/**
     * 	@property {String} borderColor - The border color for the polyline
     */
	this.borderColor = borderColor || '#000';

	/**
     * 	@property {String} insideColor - The inside color for the polyline
     */
	this.insideColor = insideColor || yom.colors.DEFAULT_INSIDE_COLOR;

	/**
     * 	@property {number} zIndex - The z index of the polyline
     */
	this.zIndex = zIndex || 0;

	this.centroid = polyline.centroid;

	/**
	 *	@property {number} lineWidth - The border width (optionnal 1 is by default)
	 */
	this.lineWidth = lineWidth || 1;
};

// ----- Method(s) ----- \\
/**
 * 	Copies this into a new object of type 'yom.GraphicPolyline'
 * 	@method yom.GraphicPolyline#copy
 * 	@return {yom.GraphicPolyline} The new GraphicPolyline object
 */
yom.GraphicPolyline.prototype.copy = function () {
	return new yom.GraphicPolyline(this.polyline);
};

/**
 * 	Moves the graphic polyline by x for the x coordinate, and by y for the y coordinate
 * 	@method yom.GraphicPolyline#move
 * 	@param {number} [x=0] - The x-coordinate offset
 * 	@param {number} [y=0] - The y-coordinate offset
 */
yom.GraphicPolyline.prototype.move = function (x, y) {
	this.polyline.move(x, y);
};

/**
 * 	Draw the graphic polyline.
 * 	@method yom.GraphicPolyline#draw
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.draw = function(drawManager) {
	drawManager.drawPolyline(this);
};

/**
 * 	Fill the graphic polyline with color.
 * 	@method yom.GraphicPolyline#fillWithColor
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.fillWithColor = function(drawManager) {
	// No filling possible, so drawing
	drawManager.drawPolyline(this);
};

/**
 * 	Fill the graphic polyline with image.
 * 	@method yom.GraphicPolyline#fillWithImage
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.fillWithImage = function(drawManager) {
	// No filling possible, so drawing
	drawManager.drawPolyline(this);
};

/**
 * 	Render the polyline
 * 	@method yom.GraphicPolyline#render
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.render = function(drawManager) {
	this.draw(drawManager);
};
<commit_msg>Fixed function copy for GraphicPolyline<commit_after>/**
 * 	@author       Rémi MARTIN <martinremi60@gmail.com>
 * 	@copyright    2014 Rémi MARTIN
 */

/**
 * 	Creates a new GraphicPolyline object.
 * 	The GraphicPolyline is defined with a polyline and some colors.
 * 	@class GraphicPolyline
 * 	@classdesc yom - GraphicPolyline
 * 	@constructor
 * 	@param {yom.Polyline} [polyline] - The polyline to copy
 * 	@param {number} [zIndex] - The zIndex of the polyline
 * 	@param {String} [borderColor] - The border color for the polyline
 *	@param {number} [lineWidth=1] - The border width (optionnal 1 is by default)
 * 	@param {String} [insideColor] - The inside color for the polyline
 * 	@return {yom.GrapphicPolyline} The GraphicPolyline object
 *
 *	TODO : Add color
 */
yom.GraphicPolyline = function (polyline, zIndex, borderColor, lineWidth, insideColor) {

	/**
     * 	@property {yom.Polyline} polyline - The polyline we want to display
     */
	this.polyline = polyline || {};

	/**
     * 	@property {String} borderColor - The border color for the polyline
     */
	this.borderColor = borderColor || '#000';

	/**
     * 	@property {String} insideColor - The inside color for the polyline
     */
	this.insideColor = insideColor || yom.colors.DEFAULT_INSIDE_COLOR;

	/**
     * 	@property {number} zIndex - The z index of the polyline
     */
	this.zIndex = zIndex || 0;

	this.centroid = polyline.centroid;

	/**
	 *	@property {number} lineWidth - The border width (optionnal 1 is by default)
	 */
	this.lineWidth = lineWidth || 1;
};

// ----- Method(s) ----- \\
/**
 * 	Copies this into a new object of type 'yom.GraphicPolyline'
 * 	@method yom.GraphicPolyline#copy
 * 	@return {yom.GraphicPolyline} The new GraphicPolyline object
 */
yom.GraphicPolyline.prototype.copy = function () {
	return new yom.GraphicPolyline(this.polyline, this.zIndex, this.borderColor, this.lineWidth, this.insideColor);
};

/**
 * 	Moves the graphic polyline by x for the x coordinate, and by y for the y coordinate
 * 	@method yom.GraphicPolyline#move
 * 	@param {number} [x=0] - The x-coordinate offset
 * 	@param {number} [y=0] - The y-coordinate offset
 */
yom.GraphicPolyline.prototype.move = function (x, y) {
	this.polyline.move(x, y);
};

/**
 * 	Draw the graphic polyline.
 * 	@method yom.GraphicPolyline#draw
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.draw = function(drawManager) {
	drawManager.drawPolyline(this);
};

/**
 * 	Fill the graphic polyline with color.
 * 	@method yom.GraphicPolyline#fillWithColor
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.fillWithColor = function(drawManager) {
	// No filling possible, so drawing
	drawManager.drawPolyline(this);
};

/**
 * 	Fill the graphic polyline with image.
 * 	@method yom.GraphicPolyline#fillWithImage
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.fillWithImage = function(drawManager) {
	// No filling possible, so drawing
	drawManager.drawPolyline(this);
};

/**
 * 	Render the polyline
 * 	@method yom.GraphicPolyline#render
 * 	@param {yom.DrawManager} [drawManager] - The drawManager object
 */
yom.GraphicPolyline.prototype.render = function(drawManager) {
	this.draw(drawManager);
};
<|endoftext|>