<commit_before>
var elasticsearchSqlApp = angular.module('elasticsearchSqlApp', ["ngAnimate", "ngSanitize"]);

elasticsearchSqlApp.controller('MainController', function ($scope, $http, $sce,$compile) {
	scroll_url = "_search/scroll?scroll=1m&scroll_id=";
	$scope.url = getUrl();
	$scope.showResults = false;
	$scope.error = "";
	$scope.resultsColumns =[];
	$scope.resultsRows = [];
	$scope.searchLoading = false;
	$scope.explainLoading = false;
	$scope.nextLoading = false;
  $scope.fetchAllLoading = false;
	$scope.resultExplan = false;

	$scope.scrollId = undefined;
  $scope.amountDescription = "";
  var optionsKey = "essql-options-v1";
  var fetched = 0;
  var total = 0 ;
  //checkboxes
  $scope.gotNext = false;
  $scope.config = loadOptionsFromStorageOrDefault();

  var tablePresenter = new TablePresenter('searchResult','#searchResultZone');

  /* todo move to class - options handler */
  $scope.saveConfigToStorage = function () {
    localStorage.setItem(optionsKey,JSON.stringify($scope.config));
  }
  function loadOptionsFromStorageOrDefault () {
    var defaultOptions = {
      isFlat : false,
      useOldTable : false,
      scrollSize : 10,
      alwaysScroll : false,
      isAutoSave : false,
      delimiter : ',',
      showScore : false,
      showType : false
    }
    if (typeof(Storage) !== "undefined") {
      options = localStorage.getItem(optionsKey);
      if(options!=undefined)
        return JSON.parse(options);
      else
        return defaultOptions;
    }
  }

 	// pull version and put it on the scope
    $http.get($scope.url).success(function (data) {
        $http.get($scope.url + "_nodes/" + data.name).success(function (nodeData) {
            var node = nodeData.nodes[Object.keys(nodeData.nodes)[0]];
            angular.forEach(node.plugins, function (plugin) {
                if (plugin.name === "sql") {
                    $scope.version = plugin.version;
                }
            });
        });
    });

/* todo move to class fetch*/
$scope.fetchAll = function(){

  $scope.showResults = true;

  callScrollAndFillBodyTillEnd($scope.scrollId,$scope.resultsColumns,$scope.resultsRows,true,false,true);
}
	$scope.nextSearch = function(){
		$scope.error = "";
		$scope.nextLoading = true;
		$scope.$apply();
    var needToBuildTable = false;

		if($scope.scrollId == undefined || $scope.scrollId == "" ){
			$scope.error = "tryed scrolling with empty scrollId";
			return;
		}

		$http.get($scope.url + scroll_url + $scope.scrollId)
		.success(function(data, status, headers, config) {
          var handler = ResultHandlerFactory.create(data,$scope.config.isFlat,$scope.config.showScore,$scope.config.showType);
          updateDescription(handler);
          var body = handler.getBody()

          if(body.length == undefined || body.length == 0){
          	$scope.gotNext=false;
          }
          else
          {
          	  $scope.scrollId = handler.getScrollId();
          }

          if($scope.resultsRows.length > 0){
            tablePresenter.addRows(handler.getBody());
          	$scope.resultsRows = $scope.resultsRows.concat(handler.getBody());
          }
          else {
          	$scope.resultsColumns = handler.getHead();
            $scope.resultsRows = handler.getBody();
            needToBuildTable = true;
          }

        })
        .error(function(data, status, headers, config) {
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
    	  }
    	  else {
    	  	$scope.error = JSON.stringify(data);
    	  	$scope.scrollId = undefined;
		  }
        })
        .finally(function() {
          $scope.nextLoading = false;
          $scope.$apply();
          if(needToBuildTable) {
            tablePresenter.createOrReplace($scope.resultsColumns,$scope.resultsRows);
          }

        });

	}

function updateWithScrollIfNeeded (query) {
  if(!$scope.config.alwaysScroll)
      return query;
  if(query.indexOf("USE_SCROLL")!=-1)
    return query;
  var scrollHint = "/*! USE_SCROLL("+$scope.config.scrollSize+","+120000+") */";
  if(query.indexOf("select") !=-1)
    return query.replace("select","select " + scrollHint);
  if(query.indexOf("SELECT") !=-1)
    return query.replace("SELECT","select " + scrollHint);
  return query;
}

	$scope.search = function() {
		// Reset results and error box
		$scope.error = "";
		fetched = 0;
		total = 0;
		$scope.amountDescription = 0;
		$scope.resultsColumns = [];
		$scope.resultsRows = [];
		$scope.searchLoading = true;

		$scope.resultExplan = false;
    tablePresenter.destroy();
    $scope.$apply();
		saveUrl()

    var query = window.editor.getValue();
    var selectedQuery = window.editor.getSelection();
    if(selectedQuery != "" && selectedQuery != undefined){
      query = selectedQuery;
    }
    query = updateWithScrollIfNeeded(query);
		$http.post($scope.url + "_sql", query)
		.success(function(data, status, headers, config) {
          var handler = ResultHandlerFactory.create(data,$scope.config.isFlat,$scope.config.showScore,$scope.config.showType);
          updateDescription(handler);
          if(handler.isScroll){
          	$scope.showResults=true;
          	$scope.scrollId = handler.getScrollId();
          	if($scope.config.isAutoSave){
          		searchTillEndAndExportCsv($scope.scrollId);
          	}
          	else {
          		$scope.gotNext=true;
                scrollBudy = handler.getBody();
                //not using scan type
                if(scrollBudy.length >0 ){
                    $scope.resultsColumns = handler.getHead();
                    $scope.resultsRows = scrollBudy;
                }
          	}
          }

          else {

          	if($scope.config.isAutoSave){
                $scope.showResults=true;
          		exportCSVWithoutScope(handler.getHead(),handler.getBody());
          	}
            else {
                $scope.resultsColumns = handler.getHead();
                $scope.resultsRows = handler.getBody();

            }
          }
        })
        .error(function(data, status, headers, config) {
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
    	  }
    	  else {
    	  	$scope.error = JSON.stringify(data);
		  }
        })
        .finally(function() {
          $scope.searchLoading = false;
          $scope.$apply();
          if($scope.resultsColumns.length >0){
            tablePresenter.createOrReplace($scope.resultsColumns,$scope.resultsRows);
          }

        });
	}

	$scope.explain = function() {
		// Reset results and error box
		$scope.error = "";
		$scope.resultsColumns = [];
		$scope.resultsRows = [];
		$scope.explainLoading = true;
        $scope.showResults = false;
        tablePresenter.destroy();
        $scope.resultExplan = true;
		$scope.$apply();

		saveUrl()

        var query = window.editor.getValue();
		$http.post($scope.url + "_sql/_explain", query)
		.success(function(data, status, headers, config) {
					 $scope.resultExplan = true;
				   window.explanResult.setValue(JSON.stringify(data, null, "\t"));
        })
        .error(function(data, status, headers, config) {
        	$scope.resultExplan = false;
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
    	  }
    	  else {
    	  	$scope.error = JSON.stringify(data);
		  }
        })
        .finally(function() {
          $scope.explainLoading = false;
          $scope.$apply()
        });
	}

	 function exportCSVWithoutScope(columns,rows) {
		var delimiter = $scope.config.delimiter;
		var data =arr2csvStr(columns,delimiter) ;
		for(var i=0; i<rows.length ; i++){
		data += "\n";
			data += map2csvStr(columns,rows[i],delimiter) ;
		}
		var plain = 'data:text/csv,\uFEFF;charset=utf8,' + encodeURIComponent(data);
		download(plain, "query_result.csv", "text/plain");
  		return true;
	}

      $scope.onChangeTablePresnterType = function(){
      //value = ?
      value = $scope.config.useOldTable;
      tablePresenter.destroy();
      tablePresenter.changeTableType(value,$compile,$scope);
    }

    function searchTillEndAndExportCsv (scrollId) {
      //todo: get total amount show fetched/total
      head = []
      body = []
      $scope.showResults = true;
      callScrollAndFillBodyTillEnd(scrollId,head,body,true,true,false);
    }
    function updateDescription (handler) {
        total = handler.getTotal();
        fetched += handler.getCurrentHitsSize();
        if(total == undefined){
          $scope.amountDescription = fetched
        }
        else {
          if(total == fetched){
            $scope.gotNext = false;
          }
          $scope.amountDescription = fetched + "/" + total
        }
    }
    function callScrollAndFillBodyTillEnd (scrollId,head,body,firstTime,needToExport,updatePresenter) {
    var url = $scope.url + scroll_url + scrollId;
      $http.get(url)
    .success(function(data, status, headers, config) {

          var handler = ResultHandlerFactory.create(data,$scope.isFlat);

            updateDescription(handler);
           recieved = handler.getBody()
          if(body.length > 0){
            body = body.concat(recieved);

            head = $.extend(head,handler.getHead());
            if(updatePresenter){
              tablePresenter.addRows(recieved);
            }
          }
          else {
            body = recieved;
            head = handler.getHead();
            if(updatePresenter){
             tablePresenter.createOrReplace(head,body);
            }
          }
          if(recieved == undefined || recieved.length == undefined || recieved.length == 0){
            if(firstTime){
             callScrollAndFillBodyTillEnd(handler.getScrollId(),head,body,false,needToExport,updatePresenter);
            }
            else {
              if(needToExport){
                exportCSVWithoutScope(head,body);
              }
            }
          }
          else {
            callScrollAndFillBodyTillEnd(handler.getScrollId(),head,body,false,needToExport,updatePresenter);
          }

        })
        .error(function(data, status, headers, config) {
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
        }
        else {
          $scope.error = JSON.stringify(data);
          $scope.scrollId = undefined;
      }
        })
        .finally(function() {
          $scope.nextLoading = false;
          $scope.$apply()
        });

      // body...
    }

	$scope.exportCSV = function() {
		var columns = $scope.resultsColumns ;
		var rows = $scope.resultsRows ;
		exportCSVWithoutScope(columns,rows);
	}

	$scope.getButtonContent = function(isLoading , defName) {
		var loadingContent = " Loading...";
		var returnValue = isLoading ? loadingContent : defName;
		return $sce.trustAsHtml(returnValue);
	}

	function arr2csvStr(arr,op){
		var data = arr[0];
		for(var i=1; i<arr.length ; i++){
				data += op;
				data += arr[i] ;
		}
		return data ;
	}

	function map2csvStr(columns,arr,op){
		var data = JSON.stringify(arr[columns[0]]);
		for(var i=1; i<columns.length ; i++){
				data += op;
				data += JSON.stringify(arr[columns[i]]) ;
		}
		return data ;
	}

	function getUrl() {
		var url = localStorage.getItem("lasturl");
		if(url == undefined) {
			if(location.protocol == "file") {
				url = "http://localhost:9200"
			}
			else {
				url = location.protocol+'//' + location.hostname + (location.port ? ':'+location.port : '');
			}
		}

		if(url.substr(url.length - 1, 1) != '/') {
			url += '/'
		}

		return url
	}

	function saveUrl() {
		localStorage.setItem("lasturl", $scope.url);
	}
});
<commit_msg>String crush issue on MS Excel<commit_after>
var elasticsearchSqlApp = angular.module('elasticsearchSqlApp', ["ngAnimate", "ngSanitize"]);

elasticsearchSqlApp.controller('MainController', function ($scope, $http, $sce,$compile) {
	scroll_url = "_search/scroll?scroll=1m&scroll_id=";
	$scope.url = getUrl();
	$scope.showResults = false;
	$scope.error = "";
	$scope.resultsColumns =[];
	$scope.resultsRows = [];
	$scope.searchLoading = false;
	$scope.explainLoading = false;
	$scope.nextLoading = false;
  $scope.fetchAllLoading = false;
	$scope.resultExplan = false;

	$scope.scrollId = undefined;
  $scope.amountDescription = "";
  var optionsKey = "essql-options-v1";
  var fetched = 0;
  var total = 0 ;
  //checkboxes
  $scope.gotNext = false;
  $scope.config = loadOptionsFromStorageOrDefault();

  var tablePresenter = new TablePresenter('searchResult','#searchResultZone');

  /* todo move to class - options handler */
  $scope.saveConfigToStorage = function () {
    localStorage.setItem(optionsKey,JSON.stringify($scope.config));
  }
  function loadOptionsFromStorageOrDefault () {
    var defaultOptions = {
      isFlat : false,
      useOldTable : false,
      scrollSize : 10,
      alwaysScroll : false,
      isAutoSave : false,
      delimiter : ',',
      showScore : false,
      showType : false
    }
    if (typeof(Storage) !== "undefined") {
      options = localStorage.getItem(optionsKey);
      if(options!=undefined)
        return JSON.parse(options);
      else
        return defaultOptions;
    }
  }

 	// pull version and put it on the scope
    $http.get($scope.url).success(function (data) {
        $http.get($scope.url + "_nodes/" + data.name).success(function (nodeData) {
            var node = nodeData.nodes[Object.keys(nodeData.nodes)[0]];
            angular.forEach(node.plugins, function (plugin) {
                if (plugin.name === "sql") {
                    $scope.version = plugin.version;
                }
            });
        });
    });

/* todo move to class fetch*/
$scope.fetchAll = function(){

  $scope.showResults = true;

  callScrollAndFillBodyTillEnd($scope.scrollId,$scope.resultsColumns,$scope.resultsRows,true,false,true);
}
	$scope.nextSearch = function(){
		$scope.error = "";
		$scope.nextLoading = true;
		$scope.$apply();
    var needToBuildTable = false;

		if($scope.scrollId == undefined || $scope.scrollId == "" ){
			$scope.error = "tryed scrolling with empty scrollId";
			return;
		}

		$http.get($scope.url + scroll_url + $scope.scrollId)
		.success(function(data, status, headers, config) {
          var handler = ResultHandlerFactory.create(data,$scope.config.isFlat,$scope.config.showScore,$scope.config.showType);
          updateDescription(handler);
          var body = handler.getBody()

          if(body.length == undefined || body.length == 0){
          	$scope.gotNext=false;
          }
          else
          {
          	  $scope.scrollId = handler.getScrollId();
          }

          if($scope.resultsRows.length > 0){
            tablePresenter.addRows(handler.getBody());
          	$scope.resultsRows = $scope.resultsRows.concat(handler.getBody());
          }
          else {
          	$scope.resultsColumns = handler.getHead();
            $scope.resultsRows = handler.getBody();
            needToBuildTable = true;
          }

        })
        .error(function(data, status, headers, config) {
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
    	  }
    	  else {
    	  	$scope.error = JSON.stringify(data);
    	  	$scope.scrollId = undefined;
		  }
        })
        .finally(function() {
          $scope.nextLoading = false;
          $scope.$apply();
          if(needToBuildTable) {
            tablePresenter.createOrReplace($scope.resultsColumns,$scope.resultsRows);
          }

        });

	}

function updateWithScrollIfNeeded (query) {
  if(!$scope.config.alwaysScroll)
      return query;
  if(query.indexOf("USE_SCROLL")!=-1)
    return query;
  var scrollHint = "/*! USE_SCROLL("+$scope.config.scrollSize+","+120000+") */";
  if(query.indexOf("select") !=-1)
    return query.replace("select","select " + scrollHint);
  if(query.indexOf("SELECT") !=-1)
    return query.replace("SELECT","select " + scrollHint);
  return query;
}

	$scope.search = function() {
		// Reset results and error box
		$scope.error = "";
		fetched = 0;
		total = 0;
		$scope.amountDescription = 0;
		$scope.resultsColumns = [];
		$scope.resultsRows = [];
		$scope.searchLoading = true;

		$scope.resultExplan = false;
    tablePresenter.destroy();
    $scope.$apply();
		saveUrl()

    var query = window.editor.getValue();
    var selectedQuery = window.editor.getSelection();
    if(selectedQuery != "" && selectedQuery != undefined){
      query = selectedQuery;
    }
    query = updateWithScrollIfNeeded(query);
		$http.post($scope.url + "_sql", query)
		.success(function(data, status, headers, config) {
          var handler = ResultHandlerFactory.create(data,$scope.config.isFlat,$scope.config.showScore,$scope.config.showType);
          updateDescription(handler);
          if(handler.isScroll){
          	$scope.showResults=true;
          	$scope.scrollId = handler.getScrollId();
          	if($scope.config.isAutoSave){
          		searchTillEndAndExportCsv($scope.scrollId);
          	}
          	else {
          		$scope.gotNext=true;
                scrollBudy = handler.getBody();
                //not using scan type
                if(scrollBudy.length >0 ){
                    $scope.resultsColumns = handler.getHead();
                    $scope.resultsRows = scrollBudy;
                }
          	}
          }

          else {

          	if($scope.config.isAutoSave){
                $scope.showResults=true;
          		exportCSVWithoutScope(handler.getHead(),handler.getBody());
          	}
            else {
                $scope.resultsColumns = handler.getHead();
                $scope.resultsRows = handler.getBody();

            }
          }
        })
        .error(function(data, status, headers, config) {
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
    	  }
    	  else {
    	  	$scope.error = JSON.stringify(data);
		  }
        })
        .finally(function() {
          $scope.searchLoading = false;
          $scope.$apply();
          if($scope.resultsColumns.length >0){
            tablePresenter.createOrReplace($scope.resultsColumns,$scope.resultsRows);
          }

        });
	}

	$scope.explain = function() {
		// Reset results and error box
		$scope.error = "";
		$scope.resultsColumns = [];
		$scope.resultsRows = [];
		$scope.explainLoading = true;
        $scope.showResults = false;
        tablePresenter.destroy();
        $scope.resultExplan = true;
		$scope.$apply();

		saveUrl()

        var query = window.editor.getValue();
		$http.post($scope.url + "_sql/_explain", query)
		.success(function(data, status, headers, config) {
					 $scope.resultExplan = true;
				   window.explanResult.setValue(JSON.stringify(data, null, "\t"));
        })
        .error(function(data, status, headers, config) {
        	$scope.resultExplan = false;
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
    	  }
    	  else {
    	  	$scope.error = JSON.stringify(data);
		  }
        })
        .finally(function() {
          $scope.explainLoading = false;
          $scope.$apply()
        });
	}

	 function exportCSVWithoutScope(columns,rows) {
		var delimiter = $scope.config.delimiter;
		var data =arr2csvStr(columns,delimiter) ;
		for(var i=0; i<rows.length ; i++){
		data += "\n";
			data += map2csvStr(columns,rows[i],delimiter) ;
		}
		var plain = 'data:text/csv;charset=utf8,\uFEFF' + encodeURIComponent(data);
		download(plain, "query_result.csv", "text/plain");
  		return true;
	}

      $scope.onChangeTablePresnterType = function(){
      //value = ?
      value = $scope.config.useOldTable;
      tablePresenter.destroy();
      tablePresenter.changeTableType(value,$compile,$scope);
    }

    function searchTillEndAndExportCsv (scrollId) {
      //todo: get total amount show fetched/total
      head = []
      body = []
      $scope.showResults = true;
      callScrollAndFillBodyTillEnd(scrollId,head,body,true,true,false);
    }
    function updateDescription (handler) {
        total = handler.getTotal();
        fetched += handler.getCurrentHitsSize();
        if(total == undefined){
          $scope.amountDescription = fetched
        }
        else {
          if(total == fetched){
            $scope.gotNext = false;
          }
          $scope.amountDescription = fetched + "/" + total
        }
    }
    function callScrollAndFillBodyTillEnd (scrollId,head,body,firstTime,needToExport,updatePresenter) {
    var url = $scope.url + scroll_url + scrollId;
      $http.get(url)
    .success(function(data, status, headers, config) {

          var handler = ResultHandlerFactory.create(data,$scope.isFlat);

            updateDescription(handler);
           recieved = handler.getBody()
          if(body.length > 0){
            body = body.concat(recieved);

            head = $.extend(head,handler.getHead());
            if(updatePresenter){
              tablePresenter.addRows(recieved);
            }
          }
          else {
            body = recieved;
            head = handler.getHead();
            if(updatePresenter){
             tablePresenter.createOrReplace(head,body);
            }
          }
          if(recieved == undefined || recieved.length == undefined || recieved.length == 0){
            if(firstTime){
             callScrollAndFillBodyTillEnd(handler.getScrollId(),head,body,false,needToExport,updatePresenter);
            }
            else {
              if(needToExport){
                exportCSVWithoutScope(head,body);
              }
            }
          }
          else {
            callScrollAndFillBodyTillEnd(handler.getScrollId(),head,body,false,needToExport,updatePresenter);
          }

        })
        .error(function(data, status, headers, config) {
          if(data == "") {
            $scope.error = "Error occured! response is not avalible.";
        }
        else {
          $scope.error = JSON.stringify(data);
          $scope.scrollId = undefined;
      }
        })
        .finally(function() {
          $scope.nextLoading = false;
          $scope.$apply()
        });

      // body...
    }

	$scope.exportCSV = function() {
		var columns = $scope.resultsColumns ;
		var rows = $scope.resultsRows ;
		exportCSVWithoutScope(columns,rows);
	}

	$scope.getButtonContent = function(isLoading , defName) {
		var loadingContent = " Loading...";
		var returnValue = isLoading ? loadingContent : defName;
		return $sce.trustAsHtml(returnValue);
	}

	function arr2csvStr(arr,op){
		var data = arr[0];
		for(var i=1; i<arr.length ; i++){
				data += op;
				data += arr[i] ;
		}
		return data ;
	}

	function map2csvStr(columns,arr,op){
		var data = JSON.stringify(arr[columns[0]]);
		for(var i=1; i<columns.length ; i++){
				data += op;
				data += JSON.stringify(arr[columns[i]]) ;
		}
		return data ;
	}

	function getUrl() {
		var url = localStorage.getItem("lasturl");
		if(url == undefined) {
			if(location.protocol == "file") {
				url = "http://localhost:9200"
			}
			else {
				url = location.protocol+'//' + location.hostname + (location.port ? ':'+location.port : '');
			}
		}

		if(url.substr(url.length - 1, 1) != '/') {
			url += '/'
		}

		return url
	}

	function saveUrl() {
		localStorage.setItem("lasturl", $scope.url);
	}
});
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2014 FusionCharts Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
(function() {
    var fc = angular.module('ng-fusioncharts', []);

    fc.directive('fusioncharts', ['$http', function($http) {
        return {
            scope: {
                width: '@',
                height: '@',
                data: '@',
                dataset: '@',
                categories: '@',
                chart: '@',
                linkeddata: '@',
                trendlines: '@',
                vtrendlines: '@',
                annotations: '@',
                colorrange: '@',
                lineset: '@',
                axis: '@',
                connectors: '@',
                pointers: '@',
                value: '@',
                processes: '@',
                tasks: '@',
                rows: '@',
                columns: '@',
                map: '@',
                markers: '@'
            },
            link: function(scope, element, attrs) {
                var observeConf = {
                        // non-data componenet observers
                        NDCObserver: {
                            'width': {
                                ifExist: false,
                                observer: function(newVal) {
                                    if (newVal && chartConfigObject.width != newVal) {
                                        chartConfigObject.width = newVal;
                                        chart.resizeTo(scope.width, scope.height);
                                    }
                                }
                            },
                            'height': {
                                ifExist: false,
                                observer: function(newVal) {
                                    if (newVal && chartConfigObject.height != newVal) {
                                        chartConfigObject.height = newVal;
                                        chart.resizeTo(scope.width, scope.height);
                                    }
                                }
                            },

                            'datasource': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (dataStringStore.dataSource != newVal) {
                                        dataStringStore.dataSource = newVal;
                                        if (chartConfigObject.dataFormat === 'json') {
                                            chartConfigObject.dataSource = JSON.parse(newVal);
                                            setChartData();
                                        } else {
                                            chartConfigObject.dataSource = newVal;
                                            if (chartConfigObject.dataFormat === 'xml') {
                                                chart.setXMLData(newVal);
                                            } else if (chartConfigObject.dataFormat === 'jsonurl') {
                                                chart.setJSONUrl(newVal);
                                            } else if (chartConfigObject.dataFormat === 'xmlurl') {
                                                chart.setXMLUrl(newVal);
                                            }
                                        }
                                    }
                                }
                            },
                            'type': {
                                ifExist: false,
                                observer: function(newVal) {
                                    if (newVal && chartConfigObject.type != newVal) {
                                        chartConfigObject.type = newVal;
                                        createFCChart();
                                    }
                                }
                            },
                            'config': {
                                ifExist: false,
                                observer: function(newVal) {
                                    var configObj,
                                        attr,
                                        doReRender = false;
                                    if (newVal) {
                                        configObj = JSON.parse(newVal);
                                        for (attr in configObj) {
                                            // detect the value change
                                            if (chartConfigObject[attr] != configObj[attr]) {
                                                doReRender = true;
                                                chartConfigObject[attr] = configObj[attr];
                                            }
                                        }
                                        if (doReRender) {
                                            createFCChart();
                                        }
                                    }
                                }
                            }
                        },
                        // data componenet observers
                        DCObserver: {
                            'chart': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.chart != newVal) {
                                        dataStringStore.chart = newVal;
                                        chartConfigObject.dataSource.chart = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'data': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.data != newVal) {
                                        dataStringStore.data = newVal;
                                        chartConfigObject.dataSource.data = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'categories': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.categories != newVal) {
                                        dataStringStore.categories = newVal;
                                        chartConfigObject.dataSource.categories = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'dataset': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.dataset != newVal) {
                                        dataStringStore.dataset = newVal;
                                        chartConfigObject.dataSource.dataset = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'linkeddata': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.linkeddata != newVal) {
                                        dataStringStore.linkeddata = newVal;
                                        chartConfigObject.dataSource.linkeddata = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'trendlines': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.trendlines != newVal) {
                                        dataStringStore.trendlines = newVal;
                                        chartConfigObject.dataSource.trendlines = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'vtrendlines': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.vtrendlines != newVal) {
                                        dataStringStore.vtrendlines = newVal;
                                        chartConfigObject.dataSource.vtrendlines = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'annotations': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.annotations != newVal) {
                                        dataStringStore.annotations = newVal;
                                        chartConfigObject.dataSource.annotations = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'colorrange': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.colorrange != newVal) {
                                        dataStringStore.colorrange = newVal;
                                        chartConfigObject.dataSource.colorrange = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'lineset': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.lineset != newVal) {
                                        dataStringStore.lineset = newVal;
                                        chartConfigObject.dataSource.lineset = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'axis': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.axis != newVal) {
                                        dataStringStore.axis = newVal;
                                        chartConfigObject.dataSource.axis = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'connectors': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.connectors != newVal) {
                                        dataStringStore.connectors = newVal;
                                        chartConfigObject.dataSource.connectors = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'pointers': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.pointers != newVal) {
                                        dataStringStore.pointers = newVal;
                                        chartConfigObject.dataSource.pointers = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'value': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.value != newVal) {
                                        dataStringStore.value = newVal;
                                        chartConfigObject.dataSource.value = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'processes': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.processes != newVal) {
                                        dataStringStore.processes = newVal;
                                        chartConfigObject.dataSource.processes = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'tasks': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.tasks != newVal) {
                                        dataStringStore.tasks = newVal;
                                        chartConfigObject.dataSource.tasks = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'rows': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.rows != newVal) {
                                        dataStringStore.rows = newVal;
                                        chartConfigObject.dataSource.rows = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'columns': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.columns != newVal) {
                                        dataStringStore.columns = newVal;
                                        chartConfigObject.dataSource.columns = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'map': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.map != newVal) {
                                        dataStringStore.map = newVal;
                                        chartConfigObject.dataSource.map = JSON.parse(newVal);
                                        setChartData();
                                    }
                                },
                            },
                            'markers': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.markers != newVal) {
                                        dataStringStore.markers = newVal;
                                        chartConfigObject.dataSource.markers = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                        }
                    },
                    eventsObj = {},
                    attribs = Object.keys(attrs),
                    chart = null,
                    events = {
                        '*': function(ev, props) {
                            if (eventsObj.hasOwnProperty(ev.eventType)) {
                                eventsObj[ev.eventType](ev, props);
                            }
                        }
                    },
                    setDataTimer,
                    setChartData = function() {
                        // clear previous dataUpdate timer
                        if (setDataTimer) {
                            clearTimeout(setDataTimer);
                        }
                        // Update the data with setTimeout
                        // This will solve the issue of consiquitive data update within very small interval
                        setDataTimer = setTimeout(function() {
                            if (chart && chart.setJSONData) {
                                chart.setJSONData(chartConfigObject.dataSource);
                            }
                        }, 100);
                    },
                    createFCChart = function() {
                        // dispose if previous chart exists
                        if (chart && chart.dispose) {
                            chart.dispose();
                        }
                        chart = new FusionCharts(chartConfigObject);
					    /* @todo validate the ready function whether it can be replaced in a better way */
                        angular.element(document).ready(function(){
                            element.ready(function(){
                                 // Render the chart only when angular is done compiling the element and DOM.
                                chart = chart.render();
                                scope[attrs.chartobject] = chart;
                            });
                        });
                    },
                    dataStringStore = {},
                    i,
                    attr,
                    _eobj,
                    key,
                    observableAttr,
                    chartConfigObject,
                    configObj,
                    dataComponent,
                    eventScopeArr,
                    l;

                if (attrs.events) {
                    eventScopeArr = attrs.events.split(".");
                    l = eventScopeArr.length;
                    _eobj = scope.$parent;
                    for (i = 0; i < l; i += 1){
                        _eobj = _eobj && _eobj[eventScopeArr[i]];
                    }
                    if (_eobj) {
                        for (key in _eobj) {
                            if (_eobj.hasOwnProperty(key)) {
                                eventsObj[key.toLowerCase()] = _eobj[key];
                            }
                        }
                    }
                }
                for (i = 0; i < attribs.length; i++) {
                    attr = attribs[i];
                    if (attr.match(/^on/i)) {
                        key = attr.slice(2).toLowerCase();
                        eventsObj[key] = scope.$parent[attrs[attr]];
                    }
                }

                chartConfigObject = {
                    type: attrs.type,
                    width: attrs.width,
                    height: attrs.height,
                    renderAt: element[0],
                    id: attrs.chartid,
                    dataFormat: attrs.dataformat || 'json',
                    dataSource: {},
                    events: events
                };

                for (observableAttr in observeConf.NDCObserver) {
                    attrConfig = observeConf.NDCObserver[observableAttr];
                    if (attrConfig.ifExist === false || attrs[observableAttr]) {
                        attrs.$observe(observableAttr, attrConfig.observer);
                    }
                }

                if (attrs.datasource) {
                    chartConfigObject.dataSource = (chartConfigObject.dataFormat === 'json') ? JSON.parse(attrs.datasource) : attrs.datasource;
                    dataStringStore.dataSource = attrs.datasource;
                }

                for (observableAttr in observeConf.DCObserver) {
                    attrConfig = observeConf.DCObserver[observableAttr];
                    dataComponent = attrs[observableAttr];
                    if (dataComponent) {
                        attrs.$observe(observableAttr, attrConfig.observer);
                        dataStringStore[observableAttr] = dataComponent;
                        if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource === "object") {
                            chartConfigObject.dataSource[observableAttr] = JSON.parse(dataComponent);
                        }
                    } else if (attrConfig.ifExist === false) {
                        attrs.$observe(observableAttr, attrConfig.observer);
                    }
                }

                // add configurations from config
                if (attrs.config) {
                    configObj = JSON.parse(attrs.config);
                    for (attr in configObj) {
                        chartConfigObject[attr] = configObj[attr];
                    }
                }

                createFCChart();

            }
        };
    }]);
}());
<commit_msg>Indentation vorrection of todo<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2014 FusionCharts Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
(function() {
    var fc = angular.module('ng-fusioncharts', []);

    fc.directive('fusioncharts', ['$http', function($http) {
        return {
            scope: {
                width: '@',
                height: '@',
                data: '@',
                dataset: '@',
                categories: '@',
                chart: '@',
                linkeddata: '@',
                trendlines: '@',
                vtrendlines: '@',
                annotations: '@',
                colorrange: '@',
                lineset: '@',
                axis: '@',
                connectors: '@',
                pointers: '@',
                value: '@',
                processes: '@',
                tasks: '@',
                rows: '@',
                columns: '@',
                map: '@',
                markers: '@'
            },
            link: function(scope, element, attrs) {
                var observeConf = {
                        // non-data componenet observers
                        NDCObserver: {
                            'width': {
                                ifExist: false,
                                observer: function(newVal) {
                                    if (newVal && chartConfigObject.width != newVal) {
                                        chartConfigObject.width = newVal;
                                        chart.resizeTo(scope.width, scope.height);
                                    }
                                }
                            },
                            'height': {
                                ifExist: false,
                                observer: function(newVal) {
                                    if (newVal && chartConfigObject.height != newVal) {
                                        chartConfigObject.height = newVal;
                                        chart.resizeTo(scope.width, scope.height);
                                    }
                                }
                            },

                            'datasource': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (dataStringStore.dataSource != newVal) {
                                        dataStringStore.dataSource = newVal;
                                        if (chartConfigObject.dataFormat === 'json') {
                                            chartConfigObject.dataSource = JSON.parse(newVal);
                                            setChartData();
                                        } else {
                                            chartConfigObject.dataSource = newVal;
                                            if (chartConfigObject.dataFormat === 'xml') {
                                                chart.setXMLData(newVal);
                                            } else if (chartConfigObject.dataFormat === 'jsonurl') {
                                                chart.setJSONUrl(newVal);
                                            } else if (chartConfigObject.dataFormat === 'xmlurl') {
                                                chart.setXMLUrl(newVal);
                                            }
                                        }
                                    }
                                }
                            },
                            'type': {
                                ifExist: false,
                                observer: function(newVal) {
                                    if (newVal && chartConfigObject.type != newVal) {
                                        chartConfigObject.type = newVal;
                                        createFCChart();
                                    }
                                }
                            },
                            'config': {
                                ifExist: false,
                                observer: function(newVal) {
                                    var configObj,
                                        attr,
                                        doReRender = false;
                                    if (newVal) {
                                        configObj = JSON.parse(newVal);
                                        for (attr in configObj) {
                                            // detect the value change
                                            if (chartConfigObject[attr] != configObj[attr]) {
                                                doReRender = true;
                                                chartConfigObject[attr] = configObj[attr];
                                            }
                                        }
                                        if (doReRender) {
                                            createFCChart();
                                        }
                                    }
                                }
                            }
                        },
                        // data componenet observers
                        DCObserver: {
                            'chart': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.chart != newVal) {
                                        dataStringStore.chart = newVal;
                                        chartConfigObject.dataSource.chart = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'data': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.data != newVal) {
                                        dataStringStore.data = newVal;
                                        chartConfigObject.dataSource.data = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'categories': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.categories != newVal) {
                                        dataStringStore.categories = newVal;
                                        chartConfigObject.dataSource.categories = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'dataset': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.dataset != newVal) {
                                        dataStringStore.dataset = newVal;
                                        chartConfigObject.dataSource.dataset = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'linkeddata': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.linkeddata != newVal) {
                                        dataStringStore.linkeddata = newVal;
                                        chartConfigObject.dataSource.linkeddata = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'trendlines': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.trendlines != newVal) {
                                        dataStringStore.trendlines = newVal;
                                        chartConfigObject.dataSource.trendlines = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'vtrendlines': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.vtrendlines != newVal) {
                                        dataStringStore.vtrendlines = newVal;
                                        chartConfigObject.dataSource.vtrendlines = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'annotations': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.annotations != newVal) {
                                        dataStringStore.annotations = newVal;
                                        chartConfigObject.dataSource.annotations = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'colorrange': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.colorrange != newVal) {
                                        dataStringStore.colorrange = newVal;
                                        chartConfigObject.dataSource.colorrange = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'lineset': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.lineset != newVal) {
                                        dataStringStore.lineset = newVal;
                                        chartConfigObject.dataSource.lineset = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'axis': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.axis != newVal) {
                                        dataStringStore.axis = newVal;
                                        chartConfigObject.dataSource.axis = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'connectors': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.connectors != newVal) {
                                        dataStringStore.connectors = newVal;
                                        chartConfigObject.dataSource.connectors = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'pointers': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.pointers != newVal) {
                                        dataStringStore.pointers = newVal;
                                        chartConfigObject.dataSource.pointers = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'value': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.value != newVal) {
                                        dataStringStore.value = newVal;
                                        chartConfigObject.dataSource.value = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'processes': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.processes != newVal) {
                                        dataStringStore.processes = newVal;
                                        chartConfigObject.dataSource.processes = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'tasks': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.tasks != newVal) {
                                        dataStringStore.tasks = newVal;
                                        chartConfigObject.dataSource.tasks = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'rows': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.rows != newVal) {
                                        dataStringStore.rows = newVal;
                                        chartConfigObject.dataSource.rows = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'columns': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.columns != newVal) {
                                        dataStringStore.columns = newVal;
                                        chartConfigObject.dataSource.columns = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                            'map': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.map != newVal) {
                                        dataStringStore.map = newVal;
                                        chartConfigObject.dataSource.map = JSON.parse(newVal);
                                        setChartData();
                                    }
                                },
                            },
                            'markers': {
                                ifExist: true,
                                observer: function(newVal) {
                                    if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource == "object" && dataStringStore.markers != newVal) {
                                        dataStringStore.markers = newVal;
                                        chartConfigObject.dataSource.markers = JSON.parse(newVal);
                                        setChartData();
                                    }
                                }
                            },
                        }
                    },
                    eventsObj = {},
                    attribs = Object.keys(attrs),
                    chart = null,
                    events = {
                        '*': function(ev, props) {
                            if (eventsObj.hasOwnProperty(ev.eventType)) {
                                eventsObj[ev.eventType](ev, props);
                            }
                        }
                    },
                    setDataTimer,
                    setChartData = function() {
                        // clear previous dataUpdate timer
                        if (setDataTimer) {
                            clearTimeout(setDataTimer);
                        }
                        // Update the data with setTimeout
                        // This will solve the issue of consiquitive data update within very small interval
                        setDataTimer = setTimeout(function() {
                            if (chart && chart.setJSONData) {
                                chart.setJSONData(chartConfigObject.dataSource);
                            }
                        }, 100);
                    },
                    createFCChart = function() {
                        // dispose if previous chart exists
                        if (chart && chart.dispose) {
                            chart.dispose();
                        }
                        chart = new FusionCharts(chartConfigObject);
                        /* @todo validate the ready function whether it can be replaced in a better way */
                        angular.element(document).ready(function(){
                            element.ready(function(){
                                 // Render the chart only when angular is done compiling the element and DOM.
                                chart = chart.render();
                                scope[attrs.chartobject] = chart;
                            });
                        });
                    },
                    dataStringStore = {},
                    i,
                    attr,
                    _eobj,
                    key,
                    observableAttr,
                    chartConfigObject,
                    configObj,
                    dataComponent,
                    eventScopeArr,
                    l;

                if (attrs.events) {
                    eventScopeArr = attrs.events.split(".");
                    l = eventScopeArr.length;
                    _eobj = scope.$parent;
                    for (i = 0; i < l; i += 1){
                        _eobj = _eobj && _eobj[eventScopeArr[i]];
                    }
                    if (_eobj) {
                        for (key in _eobj) {
                            if (_eobj.hasOwnProperty(key)) {
                                eventsObj[key.toLowerCase()] = _eobj[key];
                            }
                        }
                    }
                }
                for (i = 0; i < attribs.length; i++) {
                    attr = attribs[i];
                    if (attr.match(/^on/i)) {
                        key = attr.slice(2).toLowerCase();
                        eventsObj[key] = scope.$parent[attrs[attr]];
                    }
                }

                chartConfigObject = {
                    type: attrs.type,
                    width: attrs.width,
                    height: attrs.height,
                    renderAt: element[0],
                    id: attrs.chartid,
                    dataFormat: attrs.dataformat || 'json',
                    dataSource: {},
                    events: events
                };

                for (observableAttr in observeConf.NDCObserver) {
                    attrConfig = observeConf.NDCObserver[observableAttr];
                    if (attrConfig.ifExist === false || attrs[observableAttr]) {
                        attrs.$observe(observableAttr, attrConfig.observer);
                    }
                }

                if (attrs.datasource) {
                    chartConfigObject.dataSource = (chartConfigObject.dataFormat === 'json') ? JSON.parse(attrs.datasource) : attrs.datasource;
                    dataStringStore.dataSource = attrs.datasource;
                }

                for (observableAttr in observeConf.DCObserver) {
                    attrConfig = observeConf.DCObserver[observableAttr];
                    dataComponent = attrs[observableAttr];
                    if (dataComponent) {
                        attrs.$observe(observableAttr, attrConfig.observer);
                        dataStringStore[observableAttr] = dataComponent;
                        if (chartConfigObject.dataFormat === 'json' && typeof chartConfigObject.dataSource === "object") {
                            chartConfigObject.dataSource[observableAttr] = JSON.parse(dataComponent);
                        }
                    } else if (attrConfig.ifExist === false) {
                        attrs.$observe(observableAttr, attrConfig.observer);
                    }
                }

                // add configurations from config
                if (attrs.config) {
                    configObj = JSON.parse(attrs.config);
                    for (attr in configObj) {
                        chartConfigObject[attr] = configObj[attr];
                    }
                }

                createFCChart();

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


<commit_before>/*
 * Licensed to Apereo under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Apereo licenses this file to you 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 the following location:
 *
 *   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.
 */
'use strict';
require(['./config', './js/login-config'], function(config, loginConfig) {
  require.config(config); // eslint-disable-line angular/module-getter

  require(['angular', 'jquery', 'my-app'], function(angular, $) {
    // Idea taken from
    // https://blog.mariusschulz.com/2014/10/22/asynchronously-bootstrapping-angularjs-applications-with-server-side-data
    doLogin().then(bootstrapApplication)
      .catch(function() {
        angular.element('#loading-splash').html(
          'An error has occurred during loading, ' +
          'please try refreshing the page. If the issue persists please ' +
          'contact the helpdesk.');
      });

    /**
    * Bootstrap the application like normal now
    */
    function bootstrapApplication() {
      angular.bootstrap(document, ['my-app']);
      // eslint-disable-next-line no-undef
      cssVars({shadowDOM: true, watch: true});
    }

    /**
    * Checks if the last login is still valid (4 hour timeout)
    * @param  {Object} $sessionStorage
    * @return {boolean} is the last login valid
    */
    function lastLoginValid($sessionStorage) {
      var timeLapseBetweenLogins = 14400000; // 4 hours
      if ($sessionStorage.portal && $sessionStorage.portal.lastAccessed) {
        var now = (new Date()).getTime();
        if (now - $sessionStorage.portal.lastAccessed <=
            timeLapseBetweenLogins) {
          return true;
        }
      }
      return false;
    }

    /**
     * Do the login
     * @return {Promise} the Promised login
     */
    function doLogin() {
      // init stuff
      var initInjector = angular.injector(['ng', 'ngStorage']);
      var $sessionStorage = initInjector.get('$sessionStorage');

      // login stuff
      if (loginConfig.loginURL && !lastLoginValid($sessionStorage)) {
        // assume not valid, go get a username and bootstrap the user
        var $http = initInjector.get('$http');
        return $http
        .get(loginConfig.loginURL)
        .then(function(response) {
          if ('success' === response.data.status
          || response.data.username === 'guest') {
            // store some meta data for caching reason
            if (!$sessionStorage.portal) {
              $sessionStorage.portal = {};
            }
            $sessionStorage.portal.lastAccessed = (new Date).getTime();
            $sessionStorage.portal.username = response.data.username;
            // for some really weird reason the $sessionStorage here isn't being
            // persisted to real session storage, so we have to do it manually.
            $sessionStorage.$apply();
          }
          return response; // Returning response for promise chaining
        });
      } else {
        // the cache is still valid with a valid session, carry on
        var $q = initInjector.get('$q');
        return $q.resolve(loginConfig.loginURL
          ? 'Login cache still valid from previous login'
          : 'Silent login not configured.');
      }
    }
  });
});
<commit_msg>fix: rm watch configuration from cssVars<commit_after>/*
 * Licensed to Apereo under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Apereo licenses this file to you 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 the following location:
 *
 *   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.
 */
'use strict';
require(['./config', './js/login-config'], function(config, loginConfig) {
  require.config(config); // eslint-disable-line angular/module-getter

  require(['angular', 'jquery', 'my-app'], function(angular, $) {
    // Idea taken from
    // https://blog.mariusschulz.com/2014/10/22/asynchronously-bootstrapping-angularjs-applications-with-server-side-data
    doLogin().then(bootstrapApplication)
      .catch(function() {
        angular.element('#loading-splash').html(
          'An error has occurred during loading, ' +
          'please try refreshing the page. If the issue persists please ' +
          'contact the helpdesk.');
      });

    /**
    * Bootstrap the application like normal now
    */
    function bootstrapApplication() {
      angular.bootstrap(document, ['my-app']);
      setTimeout(function() {
        // eslint-disable-next-line no-undef
        cssVars({shadowDOM: true});
      }, 1000);
    }

    /**
    * Checks if the last login is still valid (4 hour timeout)
    * @param  {Object} $sessionStorage
    * @return {boolean} is the last login valid
    */
    function lastLoginValid($sessionStorage) {
      var timeLapseBetweenLogins = 14400000; // 4 hours
      if ($sessionStorage.portal && $sessionStorage.portal.lastAccessed) {
        var now = (new Date()).getTime();
        if (now - $sessionStorage.portal.lastAccessed <=
            timeLapseBetweenLogins) {
          return true;
        }
      }
      return false;
    }

    /**
     * Do the login
     * @return {Promise} the Promised login
     */
    function doLogin() {
      // init stuff
      var initInjector = angular.injector(['ng', 'ngStorage']);
      var $sessionStorage = initInjector.get('$sessionStorage');

      // login stuff
      if (loginConfig.loginURL && !lastLoginValid($sessionStorage)) {
        // assume not valid, go get a username and bootstrap the user
        var $http = initInjector.get('$http');
        return $http
        .get(loginConfig.loginURL)
        .then(function(response) {
          if ('success' === response.data.status
          || response.data.username === 'guest') {
            // store some meta data for caching reason
            if (!$sessionStorage.portal) {
              $sessionStorage.portal = {};
            }
            $sessionStorage.portal.lastAccessed = (new Date).getTime();
            $sessionStorage.portal.username = response.data.username;
            // for some really weird reason the $sessionStorage here isn't being
            // persisted to real session storage, so we have to do it manually.
            $sessionStorage.$apply();
          }
          return response; // Returning response for promise chaining
        });
      } else {
        // the cache is still valid with a valid session, carry on
        var $q = initInjector.get('$q');
        return $q.resolve(loginConfig.loginURL
          ? 'Login cache still valid from previous login'
          : 'Silent login not configured.');
      }
    }
  });
});
<|endoftext|>


<commit_before>jQuery(function() {

    function setEditor(popup) {
        var value = popup.find('>:selected').val();
        var parent_form = popup.parents('form');
        var content_field_name = popup.attr('name').replace(/type$/, 'content');
        var content_field = parent_form.find('textarea[name=' + content_field_name + ']');
        if (value == 'wymeditor') {
            content_field.wymeditor({
                updateSelector: "input:submit",
                updateEvent: "click",
            });
        } else {
            content_field.siblings('div.wym_box').remove();
            content_field.css('display', 'inline');
        }
    }
    jQuery('#pagelet-form select[name=type],' +
           'body.pagelets-pagelet.change-form select[name=type],' +
           'body.pagelets-page.change-form select[name$=type]').change(function(event) {
        var popup = $(this);
        setEditor(popup);
    }).each(function (i, elem) {
        setEditor($(elem));
    });

});<commit_msg>Altered setEditor to updated text box when it changes content type.<commit_after>jQuery(function() {

    function setEditor(popup) {
        var value = popup.find('>:selected').val();
        var parent_form = popup.parents('form');
        var content_field_name = popup.attr('name').replace(/type$/, 'content');
        var content_field = parent_form.find('textarea[name=' + content_field_name + ']');
        if (value == 'wymeditor') {
            content_field.wymeditor({
                updateSelector: "input:submit",
                updateEvent: "click",
            });
        } else {
            jQuery.each(WYMeditor.INSTANCES, function() {
              console.log(this._element.attr('name'));
              console.log(content_field.attr('name'));
              if(this._element.attr('name') == content_field.attr('name')){
                  this.update();
                  $(this._box).remove();
                  $(this._element).show();
                  delete this;
              }
            });
            content_field.siblings('div.wym_box').remove();
            content_field.css('display', 'inline');
        }
    }
    jQuery('#pagelet-form select[name=type],' +
           'body.pagelets-pagelet.change-form select[name=type],' +
           'body.pagelets-page.change-form select[name$=type]').change(function(event) {
        var popup = $(this);
        setEditor(popup);
    }).each(function (i, elem) {
        setEditor($(elem));
    });

});
<|endoftext|>