<commit_before>Kamato.register.controller('easyDBCtrl', function ($scope, $http, $modal, ngDialog, $rootScope){

	var db_link = "./manage/db/";

	$http.get(db_link).
        success(function(db) {
            $scope.tables = db.data;
            $scope.table_click(db.data[0], 15, 1);
        });

    $scope.t_d_more = [];
    var jsonTemp = {};
    var viewing_table = "";

    $scope.findData = function() {
    	var link = db_link + $scope.default_view_table;
    	var searchQuery;
    	try {
    		searchQuery = {"query": JSON.parse($scope.command_sample)};
    	}
    	catch(e) {
    		searchQuery = {"query": {}};
    	}
    	$http.post(link, searchQuery).success(function(schema) {
        	var t_d_temp = schema.data.list;
        	$scope.t_head = schema.data.list[0];
 			$scope.colspan = Object.keys(schema.data.list[0]).length +1; //+1是del button欄位
        	angular.forEach(t_d_temp, function(list_value, list_key){
        		angular.forEach(t_d_temp[list_key], function(value, key){
        			var value_id = t_d_temp[list_key]._id;
        			if(typeof(value) == "object" && value != null){
        				//存json
        				jsonTemp[value_id+key] = value;
        				$scope.t_d_more.push(jsonTemp);
        				//json換註解
        				t_d_temp[list_key][key] = "json file"
        			}
        			$scope.t_d = t_d_temp;

        		})
        	});
    	});
    }

    var first_row_id = 0;

    $scope.option_index = 2;          //page
    $scope.default_rows = 15;
    $scope.rows_options = [
        {'num': 5},
        {'num': 10},
        {'num': 15},
        {'num': 20}
    ]

    $scope.custom_rows = 15;  //table click

	$scope.table_click =function(name, default_table_rows, page_num){
        pre_id_attr="";    //清除上一次在其他table點擊json的事件
        $scope.warn_hint = false;   //清除在其他table點擊的刪除警告標語

        $scope.custom_rows = default_table_rows;
		viewing_table = name;
		$scope.is_show = false;
		//要把顯示json內容方框丟回table最下面,否則會被ng-repeat蓋過
		var j_text = document.getElementsByClassName("json_text");
		var table = document.getElementsByClassName("db_table");
		table[0].childNodes[1].appendChild(j_text[0]);
		$scope.default_view_table = name;

        //Get table資訊(第一筆資料id, 總筆數)
		$http.get(db_link+name).
        success(function(schema) {
            first_row_id = schema.data.max_serial_num;
            var table_length = schema.data.table_length;
            if( (table_length%default_table_rows) <= 0){
                $scope.total_pages = new Array(table_length/default_table_rows);
            }
            else{
                $scope.total_pages = new Array(parseInt(table_length/default_table_rows)+1);
            }
            //顯示table內容(預設15筆資料)
            $scope.show_table(name,default_table_rows, page_num);
        });
	}

    $scope.sch_click = function(name){
        if($scope.sch_name  == name){
            $scope.sch_name = '';
        }
        else{
            $scope.sch_name = name;
        }
    }

    $scope.sch_menu_click = function(schema_name){
        if($scope.selected_sch_menu == schema_name){
            $scope.selected_sch_menu = '';
        }
        else{
            $scope.selected_sch_menu = schema_name;
        }
    }

    $scope.sch_type_click = function(schema_name, type){
        $scope.t_head[schema_name] = type;
        $scope.sch_name = '';
        console.log($scope.t_head);
        $http.put(db_link+viewing_table, $scope.t_head).
        success(function(page_schema){
            console.log(page_schema);
        });
    }

    $scope.edit_td = function(key, id, td){
        $scope.id_td = id+td;
    }

    // ++ 需要避開delete btn
    $scope.edit_finish = function(id, edited_key, row){
        var temp_array =[];
        var temp_json = {};
        temp_json[edited_key] = row[edited_key];
        temp_array.push(temp_json);

        $http.put(db_link+viewing_table+'/'+id, temp_array[0]).success(function(edited_data_msg){
            console.log(edited_data_msg);
        })
        var e = event.target;
        var next_e = e.parentNode.nextElementSibling.firstElementChild;
        e.blur();
        next_e.focus();
    }

    $scope.show_table = function(table_name, custom_table_rows, page_num){
        //要把顯示json內容方框丟回table最下面,否則會被ng-repeat蓋過
        j_text = document.getElementsByClassName("json_text");
        table = document.getElementsByClassName("db_table");
        table[0].childNodes[1].appendChild(j_text[0]);

        $scope.page = page_num;
        //第N頁,第一筆資料的index
        var new_page_first_index = custom_table_rows*(page_num-1);
        var total_data = custom_table_rows;

        $http.get(db_link+table_name).
        success(function(page_schema){
            page_schema.data.columns['_id'] = 'Number';
            $scope.t_head = page_schema.data.columns;
        });

        $http.get(db_link+table_name+"/?q=limit "+new_page_first_index+','+custom_table_rows).
        success(function(page_schema){
            var t_d_temp = page_schema.data.list;
            // $scope.t_head = page_schema.data.list[0];
            if( Object.keys(page_schema.data.list[0] || {}).length == 0){
                //空物件
                $scope.t_d = {};
            }
            else{
                $scope.colspan = Object.keys(page_schema.data.list[0]).length +1; //+1是del button欄位
                angular.forEach(t_d_temp, function(list_value, list_key){
                    angular.forEach(t_d_temp[list_key], function(value, key){
                        var value_id = t_d_temp[list_key]._id;
                        //顯示json檔案格式
                        if(typeof(value) == "object" && value != null){
                            //存json
                            jsonTemp[value_id+key] = value;
                            $scope.t_d_more.push(jsonTemp);
                            //json換註解
                            t_d_temp[list_key][key] = "json file"
                        }
                        $scope.t_d = t_d_temp;

                    })
                })
            }
        });
    }

    var delete_table_name="";
    $scope.del_warn = function(table_name){
        delete_table_name = table_name;
    	$scope.warn_hint = true;
    	$scope.warning_text = table_name;
    }

    $scope.del_table = function(){
    	var next_table_index = $scope.tables.indexOf(delete_table_name)+1;
    	var next_table = $scope.tables[next_table_index];

        $http.delete(db_link+delete_table_name).success(function(del_msg){
            console.log(del_msg);
        })

    	$scope.tables.splice($scope.tables.indexOf(delete_table_name),1);  //從table list移除
        if (delete_table_name == viewing_table){
        	$scope.table_click(next_table, 15, 1);   //畫面換到下一個table的內容
        }
    	$scope.warn_hint = false;
    }

    $scope.close_warn_hint = function(){
    	$scope.warn_hint = false;
    }

	$scope.del_t_row = function(row){
		$scope.t_d.splice($scope.t_d.indexOf(row),1);
	}

	var pre_id="";
	$scope.is_show = false;
	var pre_id_attr="";

	$scope.show_json_file = function(id, attr_name, table_name){
        var id_attr_name = id+attr_name;

		if(pre_id_attr == id_attr_name){
			$scope.is_show = !$scope.is_show;
		}
		else{
			pre_id_attr = id_attr_name;
			$scope.is_show = true;
			var elem = document.getElementById(id);
			var j_text = document.getElementsByClassName("json_text");
			var table = document.getElementsByClassName("db_table");
			$scope.show_json= jsonTemp[id_attr_name];
			$scope.t_json = id_attr_name;

			table[0].childNodes[1].insertBefore(j_text[0], elem.nextSibling);
		}
	}

	$scope.keyword = [
		{'name': 'SELECT * FROM '},
		{'name': 'SELECT FROM  WHERE '},
		{'name': 'INSERT INTO '},
		{'name': 'UPDATE SET  WHER '},
		{'name': 'DELETE FROM  WHERE '},
	]

	$scope.show_sample = false;
	$scope.sample_list = function(){
			$scope.show_sample = true;
	}

	$scope.sql_keyword_clicked = function(name){
		$scope.command_sample = name;
		$scope.show_sample = false;
	}

	$scope.cant_close = false;
	$scope.close_sample_list = function(){
		if($scope.cant_close == false){
			$scope.show_sample = false;
		}
	}

    //=========================Create table====================
    $scope.change_page = false;
    $scope.strick_clicked  = false;
    $scope.columns = true;

    $scope.create_table = function(){
        $scope.change_page = true;

    }

    $scope.back_btn = function(){
        $scope.change_page = false;
    }

    $scope.schema_type = [
        {'type': 'String'},
        {'type': 'Number'},
        {'type': 'Boolean'},
        {'type': 'Date'},
        {'type': 'JSON'}
    ]

    $scope.submit_col_sche = {"name":"", "columns":{}};
    $scope.input_col_sche = [
        {'col_name':'', 'schema_type': ''}
    ]

    $scope.add_col_fn = function(){
        $scope.input_col_sche.push({'col_name':'', 'schema_type': ''});
        $scope.col_stricked();
    }

    $scope.submit = function(){
        $scope.submit_col_sche["name"] = $scope.table_name;
        var temp = {};
        for (var i in $scope.input_col_sche){
            temp[$scope.input_col_sche[i].col_name] = $scope.input_col_sche[i].schema_type;
        }
        $scope.submit_col_sche["columns"] = temp;
        //頁面更換
        $scope.change_page = false;
        $http.post(db_link+$scope.table_name, $scope.submit_col_sche)
        .success(function(post_table_msg){
            console.log(post_table_msg);
             $http.get(db_link).
            success(function(db) {
                console.log(db)
                $scope.tables = db.data;
                $scope.table_click(db.data[0], 15, 1);
            });
        })
        $scope.reset_create_table_form();
    }

    $scope.reset_create_table_form = function(){
        $scope.table_name = "";
        $scope.input_col_sche = [
            {'col_name':'', 'schema_type': ''}
        ]
        $scope.strick_clicked = false;
    }

    $scope.del_col_sche = function(key){
        $scope.input_col_sche.splice(key,1);
        $scope.col_stricked();
    }

    $scope.col_stricked = function(){
        console.log($scope.strick_clicked);
        if( $scope.strick_clicked == true){

            if(($scope.input_col_sche).length <= 1){
                $scope.columns = false;
            }
            else{
                $scope.columns = true;
            }
        }
        else{
            $scope.columns = true;
        }
    }
});
<commit_msg>[ EasyDB ][  更新 ] id 不能換schema<commit_after>Kamato.register.controller('easyDBCtrl', function ($scope, $http, $modal, ngDialog, $rootScope){

	var db_link = "./manage/db/";

	$http.get(db_link).
        success(function(db) {
            $scope.tables = db.data;
            $scope.table_click(db.data[0], 15, 1);
        });

    $scope.t_d_more = [];
    var jsonTemp = {};
    var viewing_table = "";

    $scope.findData = function() {
    	var link = db_link + $scope.default_view_table;
    	var searchQuery;
    	try {
    		searchQuery = {"query": JSON.parse($scope.command_sample)};
    	}
    	catch(e) {
    		searchQuery = {"query": {}};
    	}
    	$http.post(link, searchQuery).success(function(schema) {
        	var t_d_temp = schema.data.list;
        	$scope.t_head = schema.data.list[0];
 			$scope.colspan = Object.keys(schema.data.list[0]).length +1; //+1是del button欄位
        	angular.forEach(t_d_temp, function(list_value, list_key){
        		angular.forEach(t_d_temp[list_key], function(value, key){
        			var value_id = t_d_temp[list_key]._id;
        			if(typeof(value) == "object" && value != null){
        				//存json
        				jsonTemp[value_id+key] = value;
        				$scope.t_d_more.push(jsonTemp);
        				//json換註解
        				t_d_temp[list_key][key] = "json file"
        			}
        			$scope.t_d = t_d_temp;

        		})
        	});
    	});
    }

    var first_row_id = 0;

    $scope.option_index = 2;          //page
    $scope.default_rows = 15;
    $scope.rows_options = [
        {'num': 5},
        {'num': 10},
        {'num': 15},
        {'num': 20}
    ]

    $scope.custom_rows = 15;  //table click

	$scope.table_click =function(name, default_table_rows, page_num){
        pre_id_attr="";    //清除上一次在其他table點擊json的事件
        $scope.warn_hint = false;   //清除在其他table點擊的刪除警告標語

        $scope.custom_rows = default_table_rows;
		viewing_table = name;
		$scope.is_show = false;
		//要把顯示json內容方框丟回table最下面,否則會被ng-repeat蓋過
		var j_text = document.getElementsByClassName("json_text");
		var table = document.getElementsByClassName("db_table");
		table[0].childNodes[1].appendChild(j_text[0]);
		$scope.default_view_table = name;

        //Get table資訊(第一筆資料id, 總筆數)
		$http.get(db_link+name).
        success(function(schema) {
            first_row_id = schema.data.max_serial_num;
            var table_length = schema.data.table_length;
            if( (table_length%default_table_rows) <= 0){
                $scope.total_pages = new Array(table_length/default_table_rows);
            }
            else{
                $scope.total_pages = new Array(parseInt(table_length/default_table_rows)+1);
            }
            //顯示table內容(預設15筆資料)
            $scope.show_table(name,default_table_rows, page_num);
        });
	}

    $scope.sch_click = function(name){
        if($scope.sch_name  == name){
            $scope.sch_name = '';
        }
        else{
            $scope.sch_name = name;
        }
    }

    $scope.sch_menu_click = function(schema_name){
        if($scope.selected_sch_menu == schema_name){
            $scope.selected_sch_menu = '';
        }
        else{
            $scope.selected_sch_menu = schema_name;
        }
    }

    $scope.sch_type_click = function(schema_name, type){
        if(schema_name == '_id'){
            $scope.t_head[schema_name] = 'Number';
        }
        else{
            $scope.t_head[schema_name] = type;
        }
        $scope.sch_name = '';
        console.log($scope.t_head);
        $http.put(db_link+viewing_table, $scope.t_head).
        success(function(page_schema){
            console.log(page_schema);
        });
    }

    $scope.edit_td = function(key, id, td){
        $scope.id_td = id+td;
    }

    // ++ 需要避開delete btn
    $scope.edit_finish = function(id, edited_key, row){
        var temp_array =[];
        var temp_json = {};
        temp_json[edited_key] = row[edited_key];
        temp_array.push(temp_json);

        $http.put(db_link+viewing_table+'/'+id, temp_array[0]).success(function(edited_data_msg){
            console.log(edited_data_msg);
        })
        var e = event.target;
        var next_e = e.parentNode.nextElementSibling.firstElementChild;
        e.blur();
        next_e.focus();
    }

    $scope.show_table = function(table_name, custom_table_rows, page_num){
        //要把顯示json內容方框丟回table最下面,否則會被ng-repeat蓋過
        j_text = document.getElementsByClassName("json_text");
        table = document.getElementsByClassName("db_table");
        table[0].childNodes[1].appendChild(j_text[0]);

        $scope.page = page_num;
        //第N頁,第一筆資料的index
        var new_page_first_index = custom_table_rows*(page_num-1);
        var total_data = custom_table_rows;

        $http.get(db_link+table_name).
        success(function(page_schema){
            page_schema.data.columns['_id'] = 'Number';
            $scope.t_head = page_schema.data.columns;
        });

        $http.get(db_link+table_name+"/?q=limit "+new_page_first_index+','+custom_table_rows).
        success(function(page_schema){
            var t_d_temp = page_schema.data.list;
            // $scope.t_head = page_schema.data.list[0];
            if( Object.keys(page_schema.data.list[0] || {}).length == 0){
                //空物件
                $scope.t_d = {};
            }
            else{
                $scope.colspan = Object.keys(page_schema.data.list[0]).length +1; //+1是del button欄位
                angular.forEach(t_d_temp, function(list_value, list_key){
                    angular.forEach(t_d_temp[list_key], function(value, key){
                        var value_id = t_d_temp[list_key]._id;
                        //顯示json檔案格式
                        if(typeof(value) == "object" && value != null){
                            //存json
                            jsonTemp[value_id+key] = value;
                            $scope.t_d_more.push(jsonTemp);
                            //json換註解
                            t_d_temp[list_key][key] = "json file"
                        }
                        $scope.t_d = t_d_temp;

                    })
                })
            }
        });
    }

    var delete_table_name="";
    $scope.del_warn = function(table_name){
        delete_table_name = table_name;
    	$scope.warn_hint = true;
    	$scope.warning_text = table_name;
    }

    $scope.del_table = function(){
    	var next_table_index = $scope.tables.indexOf(delete_table_name)+1;
    	var next_table = $scope.tables[next_table_index];

        $http.delete(db_link+delete_table_name).success(function(del_msg){
            console.log(del_msg);
        })

    	$scope.tables.splice($scope.tables.indexOf(delete_table_name),1);  //從table list移除
        if (delete_table_name == viewing_table){
        	$scope.table_click(next_table, 15, 1);   //畫面換到下一個table的內容
        }
    	$scope.warn_hint = false;
    }

    $scope.close_warn_hint = function(){
    	$scope.warn_hint = false;
    }

	$scope.del_t_row = function(row){
		$scope.t_d.splice($scope.t_d.indexOf(row),1);
	}

	var pre_id="";
	$scope.is_show = false;
	var pre_id_attr="";

	$scope.show_json_file = function(id, attr_name, table_name){
        var id_attr_name = id+attr_name;

		if(pre_id_attr == id_attr_name){
			$scope.is_show = !$scope.is_show;
		}
		else{
			pre_id_attr = id_attr_name;
			$scope.is_show = true;
			var elem = document.getElementById(id);
			var j_text = document.getElementsByClassName("json_text");
			var table = document.getElementsByClassName("db_table");
			$scope.show_json= jsonTemp[id_attr_name];
			$scope.t_json = id_attr_name;

			table[0].childNodes[1].insertBefore(j_text[0], elem.nextSibling);
		}
	}

	$scope.keyword = [
		{'name': 'SELECT * FROM '},
		{'name': 'SELECT FROM  WHERE '},
		{'name': 'INSERT INTO '},
		{'name': 'UPDATE SET  WHER '},
		{'name': 'DELETE FROM  WHERE '},
	]

	$scope.show_sample = false;
	$scope.sample_list = function(){
			$scope.show_sample = true;
	}

	$scope.sql_keyword_clicked = function(name){
		$scope.command_sample = name;
		$scope.show_sample = false;
	}

	$scope.cant_close = false;
	$scope.close_sample_list = function(){
		if($scope.cant_close == false){
			$scope.show_sample = false;
		}
	}

    //=========================Create table====================
    $scope.change_page = false;
    $scope.strick_clicked  = false;
    $scope.columns = true;

    $scope.create_table = function(){
        $scope.change_page = true;

    }

    $scope.back_btn = function(){
        $scope.change_page = false;
    }

    $scope.schema_type = [
        {'type': 'String'},
        {'type': 'Number'},
        {'type': 'Boolean'},
        {'type': 'Date'},
        {'type': 'JSON'}
    ]

    $scope.submit_col_sche = {"name":"", "columns":{}};
    $scope.input_col_sche = [
        {'col_name':'', 'schema_type': ''}
    ]

    $scope.add_col_fn = function(){
        $scope.input_col_sche.push({'col_name':'', 'schema_type': ''});
        $scope.col_stricked();
    }

    $scope.submit = function(){
        $scope.submit_col_sche["name"] = $scope.table_name;
        var temp = {};
        for (var i in $scope.input_col_sche){
            temp[$scope.input_col_sche[i].col_name] = $scope.input_col_sche[i].schema_type;
        }
        $scope.submit_col_sche["columns"] = temp;
        //頁面更換
        $scope.change_page = false;
        $http.post(db_link+$scope.table_name, $scope.submit_col_sche)
        .success(function(post_table_msg){
            console.log(post_table_msg);
             $http.get(db_link).
            success(function(db) {
                console.log(db)
                $scope.tables = db.data;
                $scope.table_click(db.data[0], 15, 1);
            });
        })
        $scope.reset_create_table_form();
    }

    $scope.reset_create_table_form = function(){
        $scope.table_name = "";
        $scope.input_col_sche = [
            {'col_name':'', 'schema_type': ''}
        ]
        $scope.strick_clicked = false;
    }

    $scope.del_col_sche = function(key){
        $scope.input_col_sche.splice(key,1);
        $scope.col_stricked();
    }

    $scope.col_stricked = function(){
        console.log($scope.strick_clicked);
        if( $scope.strick_clicked == true){

            if(($scope.input_col_sche).length <= 1){
                $scope.columns = false;
            }
            else{
                $scope.columns = true;
            }
        }
        else{
            $scope.columns = true;
        }
    }
});
<|endoftext|>


<commit_before>/**
 * Profile Controller will use:
 *
 * profile service
 * image service
 * mail service
 * favorite service
 * genre service
 * tag service
 **/

app.controller('ProfileController', ["$routeParams", "$scope", "ProfileService", "ImageService", "MailService", "FavoritieService", "GenreService", "TagService", function($routeParams, $scope, ProfileService, ImageService, MailService, FavoriteService, GenreService, TagService) {

	$scope.profileData = null;
	$scope.alerts = [];
	$scope.imageData = null;
	$scope.mailData = null;
	$scope.favoriteData = null;
	$scope.genreData = null;
	$scope.tagService = null;

	/**
	 * Profile method
	 **/

	$scope.loadProfile = function() {
		ProfileService.fetchProfileByProfileId($routeParams.profileId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.profileData = result.data.data;
					console.log($scope.profileData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchProfileByProfileId = function() {
		ProfileService.fetchProfileByProfileName($routeParams.profileName)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.profileData = result.data.data;
					console.log($scope.profileData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Image Method
	 **/

	$scope.fetchImageByImageId = function() {
		ImageService.fetchImageByImageId($routeParams.imageId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.imageData = result.data.data;
					console.log($scope.imageData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchImageByImageProfileId = function() {
		ImageService.fetchImageByImageProfileId($routeParams.imageProfileId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.imageData = result.data.data;
					console.log($scope.imageData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Image upload from profile
	 **/
	$scope.createImage = function(image, validated) {
		if(validated === true) {
			ImageService.create(image)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
						$scope.newImage = {imageId: null, imageText:"", imageProfileId: null};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

	/**
	 * Mail Methods
	 **/

	$scope.fetchMailByMailReceiverId = function() {
		MailService.fetchMailByMailReceiverId($routeParams.mailReceiverId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.mailData = result.data.data;
					console.log($scope.mailData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchMailByMailSenderId = function() {
		MailService.fetchMailByMailSenderId($routeParams.mailSenderId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.mailData = result.data.data;
					console.log($scope.mailData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchAllMails = function() {
		MailService.fetchAllMails($routeParams.fetchAllMails()) //how do I select all mail?
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.mailData = result.data.data;
					console.log($scope.mailData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Favorite Methods
	 **/

	$scope.fetchFavoriteByFavoriteeId = function() {
		FavoriteService.fetchFavoriteByFavoriteeId($routeParams.favoriteeId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.favoriteData = result.data.data;
					console.log($scope.favoriteData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchFavoriteByFavoriterId = function() {
		FavoriteService.fetchFavoriteByFavoriterId($routeParams.favoriterId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.favoriteData = result.data.data;
					console.log($scope.favoriteData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Genre Methods
	 **/

	$scope.fetchGenreByGenreId = function() {
		GenreService.fetchGenreByGenreId($routeParams.genreId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.genreData = result.data.data;
					console.log($scope.genreData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchGenreByGenreName = function() {
		GenreService.fetchGenreByGenreName($routeParams.genreName)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.genreData = result.data.data;
					console.log($scope.genreData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchAllGenres = function() {
		GenreService.fetchAllGenres($routeParams.genreId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.genreData = result.data.data;
					console.log($scope.genreData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Tag Methods
	 **/

	$scope.fetchTagByTagId = function() {
		TagService.fetchTagByTagId($routeParams.tagId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.tagData = result.data.data;
					console.log($scope.tagData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchTagByTagName = function() {
		TagService.fetchTagByTagName($routeParams.tagName)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.tagData = result.data.data;
					console.log($scope.tagData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchAllTags = function() {
		TagService.fetchAllTags($routeParams.tagId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.tagData = result.data.data;
					console.log($scope.tagData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Create Methods
	 */

	$scope.profileCreate = function(profile, validated) {
		if(validated === true) {
			ProfileService.create(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			ImageService.create(image)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			MailService.create(mail)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			FavoriteService.create(favorite)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			TagService.create(tag)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};
	/*I didn't create any genre- not needed (I think)*/

	/**
	 * Update Methods
	 */

	$scope.profileUpdate = function(profile, validated) {
		if(validated === true) {
			ProfileService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			ImageService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			MailService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			FavoriteService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			GenreService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			TagService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

			if($scope.profileData === null){
				$scope.loadProfile();
			}
}]);
<commit_msg>changed image to formData - for input field. https://app.asana.com/0/161555263951762/170520114054348<commit_after>/**
 * Profile Controller will use:
 *
 * profile service
 * image service
 * mail service
 * favorite service
 * genre service
 * tag service
 **/

app.controller('ProfileController', ["$routeParams", "$scope", "ProfileService", "ImageService", "MailService", "FavoritieService", "GenreService", "TagService", function($routeParams, $scope, ProfileService, ImageService, MailService, FavoriteService, GenreService, TagService) {

	$scope.profileData = null;
	$scope.alerts = [];
	$scope.imageData = null;
	$scope.mailData = null;
	$scope.favoriteData = null;
	$scope.genreData = null;
	$scope.tagService = null;

	/**
	 * Profile method
	 **/

	$scope.loadProfile = function() {
		ProfileService.fetchProfileByProfileId($routeParams.profileId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.profileData = result.data.data;
					console.log($scope.profileData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchProfileByProfileId = function() {
		ProfileService.fetchProfileByProfileName($routeParams.profileName)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.profileData = result.data.data;
					console.log($scope.profileData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Image Method
	 **/

	$scope.fetchImageByImageId = function() {
		ImageService.fetchImageByImageId($routeParams.imageId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.imageData = result.data.data;
					console.log($scope.imageData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchImageByImageProfileId = function() {
		ImageService.fetchImageByImageProfileId($routeParams.imageProfileId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.imageData = result.data.data;
					console.log($scope.imageData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Image upload from profile
	 **/
	$scope.createImage = function(formData, validated) {
		if(validated === true) {
			ImageService.create(formData)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
						$scope.newImage = {imageId: null, imageText:"", imageProfileId: null};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

	/**
	 * Mail Methods
	 **/

	$scope.fetchMailByMailReceiverId = function() {
		MailService.fetchMailByMailReceiverId($routeParams.mailReceiverId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.mailData = result.data.data;
					console.log($scope.mailData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchMailByMailSenderId = function() {
		MailService.fetchMailByMailSenderId($routeParams.mailSenderId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.mailData = result.data.data;
					console.log($scope.mailData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchAllMails = function() {
		MailService.fetchAllMails($routeParams.fetchAllMails()) //how do I select all mail?
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.mailData = result.data.data;
					console.log($scope.mailData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Favorite Methods
	 **/

	$scope.fetchFavoriteByFavoriteeId = function() {
		FavoriteService.fetchFavoriteByFavoriteeId($routeParams.favoriteeId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.favoriteData = result.data.data;
					console.log($scope.favoriteData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchFavoriteByFavoriterId = function() {
		FavoriteService.fetchFavoriteByFavoriterId($routeParams.favoriterId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.favoriteData = result.data.data;
					console.log($scope.favoriteData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Genre Methods
	 **/

	$scope.fetchGenreByGenreId = function() {
		GenreService.fetchGenreByGenreId($routeParams.genreId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.genreData = result.data.data;
					console.log($scope.genreData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchGenreByGenreName = function() {
		GenreService.fetchGenreByGenreName($routeParams.genreName)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.genreData = result.data.data;
					console.log($scope.genreData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchAllGenres = function() {
		GenreService.fetchAllGenres($routeParams.genreId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.genreData = result.data.data;
					console.log($scope.genreData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Tag Methods
	 **/

	$scope.fetchTagByTagId = function() {
		TagService.fetchTagByTagId($routeParams.tagId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.tagData = result.data.data;
					console.log($scope.tagData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchTagByTagName = function() {
		TagService.fetchTagByTagName($routeParams.tagName)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.tagData = result.data.data;
					console.log($scope.tagData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	$scope.fetchAllTags = function() {
		TagService.fetchAllTags($routeParams.tagId)
			.then(function(result) {
				if(result.data.status === 200) {
					$scope.tagData = result.data.data;
					console.log($scope.tagData);
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			})
	};

	/**
	 * Create Methods
	 */

	$scope.profileCreate = function(profile, validated) {
		if(validated === true) {
			ProfileService.create(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			ImageService.create(image)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			MailService.create(mail)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			FavoriteService.create(favorite)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			TagService.create(tag)
				.then(function(result) {
					if(result.data.staus === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};
	/*I didn't create any genre- not needed (I think)*/

	/**
	 * Update Methods
	 */

	$scope.profileUpdate = function(profile, validated) {
		if(validated === true) {
			ProfileService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			ImageService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			MailService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			FavoriteService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			GenreService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});

			TagService.update(profile)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

			if($scope.profileData === null){
				$scope.loadProfile();
			}
}]);
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name ng.$q
 * @requires $rootScope
 *
 * @description
 * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
 *
 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
 * interface for interacting with an object that represents the result of an action that is
 * performed asynchronously, and may or may not be finished at any given point in time.
 *
 * From the perspective of dealing with error handling, deferred and promise APIs are to
 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
 *
 *

 *   // for the purpose of this example let's assume that variables `$q` and `scope` are
 *   // available in the current lexical scope (they could have been injected or passed in).
 *
 *   function asyncGreet(name) {
 *     var deferred = $q.defer();
 *
 *     setTimeout(function() {
 *       // since this fn executes async in a future turn of the event loop, we need to wrap
 *       // our code into an $apply call so that the model changes are properly observed.
 *       scope.$apply(function() {
 *         if (okToGreet(name)) {
 *           deferred.resolve('Hello, ' + name + '!');
 *         } else {
 *           deferred.reject('Greeting ' + name + ' is not allowed.');
 *         }
 *       });
 *     }, 1000);
 *
 *     return deferred.promise;
 *   }
 *
 *   var promise = asyncGreet('Robin Hood');
 *   promise.then(function(greeting) {
 *     alert('Success: ' + greeting);
 *   }, function(reason) {
 *     alert('Failed: ' + reason);
 *   });
 *

 *
 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
 * comes in the way of
 * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
 *
 * Additionally the promise api allows for composition that is very hard to do with the
 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
 * section on serial or parallel joining of promises.
 *
 *
 * # The Deferred API
 *
 * A new instance of deferred is constructed by calling `$q.defer()`.
 *
 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
 * that can be used for signaling the successful or unsuccessful completion of the task.
 *
 * **Methods**
 *
 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
 *   constructed via `$q.reject`, the promise will be rejected instead.
 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
 *   resolving it with a rejection constructed via `$q.reject`.
 *
 * **Properties**
 *
 * - promise – `{Promise}` – promise object associated with this deferred.
 *
 *
 * # The Promise API
 *
 * A new promise instance is created when a deferred instance is created and can be retrieved by
 * calling `deferred.promise`.
 *
 * The purpose of the promise object is to allow for interested parties to get access to the result
 * of the deferred task when it completes.
 *
 * **Methods**
 *
 * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
 *   or rejected calls one of the success or error callbacks asynchronously as soon as the result
 *   is available. The callbacks are called with a single argument the result or rejection reason.
 *
 *   This method *returns a new promise* which is resolved or rejected via the return value of the
 *   `successCallback` or `errorCallback`.
 *
 *
 * # Chaining promises
 *
 * Because calling `then` api of a promise returns a new derived promise, it is easily possible
 * to create a chain of promises:
 *
 *

 *   promiseB = promiseA.then(function(result) {
 *     return result + 1;
 *   });
 *
 *   // promiseB will be resolved immediately after promiseA is resolved and its value will be
 *   // the result of promiseA incremented by 1
 *

 *
 * It is possible to create chains of any length and since a promise can be resolved with another
 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
 * the promises at any point in the chain. This makes it possible to implement powerful apis like
 * $http's response interceptors.
 *
 *
 * # Differences between Kris Kowal's Q and $q
 *
 *  There are three main differences:
 *
 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
 *   mechanism in angular, which means faster propagation of resolution or rejection into your
 *   models and avoiding unnecessary browser repaints, which would result in flickering UI.
 * - $q promises are recognized by the templating engine in angular, which means that in templates
 *   you can treat promises attached to a scope as if they were the resulting values.
 * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
 *   all the important functionality needed for common async tasks.
 *
 *  # Testing
 *
 *

 *    it('should simulate promise', inject(function($q, $rootScope) {
 *      var deferred = $q.defer();
 *      var promise = deferred.promise;
 *      var resolvedValue;
 *
 *      promise.then(function(value) { resolvedValue = value; });
 *      expect(resolvedValue).toBeUndefined();
 *
 *      // Simulate resolving of promise
 *      deferred.resolve(123);
 *      // Note that the 'then' function does not get called synchronously.
 *      // This is because we want the promise API to always be async, whether or not
 *      // it got called synchronously or asynchronously.
 *      expect(resolvedValue).toBeUndefined();
 *
 *      // Propagate promise resolution to 'then' functions using $apply().
 *      $rootScope.$apply();
 *      expect(resolvedValue).toEqual(123);
 *    });
 *

 */
function $QProvider() {

  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
    return qFactory(function(callback) {
      $rootScope.$evalAsync(callback);
    }, $exceptionHandler);
  }];
}

/**
 * Constructs a promise manager.
 *
 * @param {function(function)} nextTick Function for executing functions in the next turn.
 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
 *     debugging purposes.
 * @returns {object} Promise manager.
 */
function qFactory(nextTick, exceptionHandler) {

  /**
   * @ngdoc
   * @name ng.$q#defer
   * @methodOf ng.$q
   * @description
   * Creates a `Deferred` object which represents a task which will finish in the future.
   *
   * @returns {Deferred} Returns a new instance of deferred.
   */
  var defer = function() {
    var pending = [],
        value, deferred;

    deferred = {

      resolve: function(val) {
        if (pending) {
          var callbacks = pending;
          pending = undefined;
          value = ref(val);

          if (callbacks.length) {
            nextTick(function() {
              var callback;
              for (var i = 0, ii = callbacks.length; i < ii; i++) {
                callback = callbacks[i];
                value.then(callback[0], callback[1]);
              }
            });
          }
        }
      },

      reject: function(reason) {
        deferred.resolve(reject(reason));
      },

      promise: {
        then: function(callback, errback) {
          var result = defer();

          var wrappedCallback = function(value) {
            try {
              result.resolve((callback || defaultCallback)(value));
            } catch(e) {
              exceptionHandler(e);
              result.reject(e);
            }
          };

          var wrappedErrback = function(reason) {
            try {
              result.resolve((errback || defaultErrback)(reason));
            } catch(e) {
              exceptionHandler(e);
              result.reject(e);
            }
          };

          if (pending) {
            pending.push([wrappedCallback, wrappedErrback]);
          } else {
            value.then(wrappedCallback, wrappedErrback);
          }

          return result.promise;
        }
      }
    };

    return deferred;
  };

  var ref = function(value) {
    if (value && value.then) return value;
    return {
      then: function(callback) {
        var result = defer();
        nextTick(function() {
          result.resolve(callback(value));
        });
        return result.promise;
      }
    };
  };

  /**
   * @ngdoc
   * @name ng.$q#reject
   * @methodOf ng.$q
   * @description
   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
   * used to forward rejection in a chain of promises. If you are dealing with the last promise in
   * a promise chain, you don't need to worry about it.
   *
   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
   * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
   * a promise error callback and you want to forward the error to the promise derived from the
   * current promise, you have to "rethrow" the error by returning a rejection constructed via
   * `reject`.
   *
   *

   *   promiseB = promiseA.then(function(result) {
   *     // success: do something and resolve promiseB
   *     //          with the old or a new result
   *     return result;
   *   }, function(reason) {
   *     // error: handle the error if possible and
   *     //        resolve promiseB with newPromiseOrValue,
   *     //        otherwise forward the rejection to promiseB
   *     if (canHandle(reason)) {
   *      // handle the error and recover
   *      return newPromiseOrValue;
   *     }
   *     return $q.reject(reason);
   *   });
   *

   *
   * @param {*} reason Constant, message, exception or an object representing the rejection reason.
   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
   */
  var reject = function(reason) {
    return {
      then: function(callback, errback) {
        var result = defer();
        nextTick(function() {
          result.resolve((errback || defaultErrback)(reason));
        });
        return result.promise;
      }
    };
  };

  /**
   * @ngdoc
   * @name ng.$q#when
   * @methodOf ng.$q
   * @description
   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
   * This is useful when you are dealing with an object that might or might not be a promise, or if
   * the promise comes from a source that can't be trusted.
   *
   * @param {*} value Value or a promise
   * @returns {Promise} Returns a single promise that will be resolved with an array of values,
   *   each value corresponding to the promise at the same index in the `promises` array. If any of
   *   the promises is resolved with a rejection, this resulting promise will be resolved with the
   *   same rejection.
   */
  var when = function(value, callback, errback) {
    var result = defer(),
        done;

    var wrappedCallback = function(value) {
      try {
        return (callback || defaultCallback)(value);
      } catch (e) {
        exceptionHandler(e);
        return reject(e);
      }
    };

    var wrappedErrback = function(reason) {
      try {
        return (errback || defaultErrback)(reason);
      } catch (e) {
        exceptionHandler(e);
        return reject(e);
      }
    };

    nextTick(function() {
      ref(value).then(function(value) {
        if (done) return;
        done = true;
        result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
      }, function(reason) {
        if (done) return;
        done = true;
        result.resolve(wrappedErrback(reason));
      });
    });

    return result.promise;
  };

  function defaultCallback(value) {
    return value;
  }

  function defaultErrback(reason) {
    return reject(reason);
  }

  /**
   * @ngdoc
   * @name ng.$q#all
   * @methodOf ng.$q
   * @description
   * Combines multiple promises into a single promise that is resolved when all of the input
   * promises are resolved.
   *
   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
   *   each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of
   *   the promises is resolved with a rejection, this resulting promise will be resolved with the
   *   same rejection.
   */
  function all(promises) {
    var deferred = defer(),
        counter = 0,
        results = isArray(promises) ? [] : {};

    forEach(promises, function(promise, key) {
      counter++;
      ref(promise).then(function(value) {
        if (results.hasOwnProperty(key)) return;
        results[key] = value;
        if (!(--counter)) deferred.resolve(results);
      }, function(reason) {
        if (results.hasOwnProperty(key)) return;
        deferred.reject(reason);
      });
    });

    if (counter === 0) {
      deferred.resolve(results);
    }

    return deferred.promise;
  }

  return {
    defer: defer,
    reject: reject,
    when: when,
    all: all
  };
}
<commit_msg>docs($q): fix incorrect @returns tag for $q.when()<commit_after>'use strict';

/**
 * @ngdoc service
 * @name ng.$q
 * @requires $rootScope
 *
 * @description
 * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
 *
 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
 * interface for interacting with an object that represents the result of an action that is
 * performed asynchronously, and may or may not be finished at any given point in time.
 *
 * From the perspective of dealing with error handling, deferred and promise APIs are to
 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
 *
 *

 *   // for the purpose of this example let's assume that variables `$q` and `scope` are
 *   // available in the current lexical scope (they could have been injected or passed in).
 *
 *   function asyncGreet(name) {
 *     var deferred = $q.defer();
 *
 *     setTimeout(function() {
 *       // since this fn executes async in a future turn of the event loop, we need to wrap
 *       // our code into an $apply call so that the model changes are properly observed.
 *       scope.$apply(function() {
 *         if (okToGreet(name)) {
 *           deferred.resolve('Hello, ' + name + '!');
 *         } else {
 *           deferred.reject('Greeting ' + name + ' is not allowed.');
 *         }
 *       });
 *     }, 1000);
 *
 *     return deferred.promise;
 *   }
 *
 *   var promise = asyncGreet('Robin Hood');
 *   promise.then(function(greeting) {
 *     alert('Success: ' + greeting);
 *   }, function(reason) {
 *     alert('Failed: ' + reason);
 *   });
 *

 *
 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
 * comes in the way of
 * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
 *
 * Additionally the promise api allows for composition that is very hard to do with the
 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
 * section on serial or parallel joining of promises.
 *
 *
 * # The Deferred API
 *
 * A new instance of deferred is constructed by calling `$q.defer()`.
 *
 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
 * that can be used for signaling the successful or unsuccessful completion of the task.
 *
 * **Methods**
 *
 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
 *   constructed via `$q.reject`, the promise will be rejected instead.
 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
 *   resolving it with a rejection constructed via `$q.reject`.
 *
 * **Properties**
 *
 * - promise – `{Promise}` – promise object associated with this deferred.
 *
 *
 * # The Promise API
 *
 * A new promise instance is created when a deferred instance is created and can be retrieved by
 * calling `deferred.promise`.
 *
 * The purpose of the promise object is to allow for interested parties to get access to the result
 * of the deferred task when it completes.
 *
 * **Methods**
 *
 * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
 *   or rejected calls one of the success or error callbacks asynchronously as soon as the result
 *   is available. The callbacks are called with a single argument the result or rejection reason.
 *
 *   This method *returns a new promise* which is resolved or rejected via the return value of the
 *   `successCallback` or `errorCallback`.
 *
 *
 * # Chaining promises
 *
 * Because calling `then` api of a promise returns a new derived promise, it is easily possible
 * to create a chain of promises:
 *
 *

 *   promiseB = promiseA.then(function(result) {
 *     return result + 1;
 *   });
 *
 *   // promiseB will be resolved immediately after promiseA is resolved and its value will be
 *   // the result of promiseA incremented by 1
 *

 *
 * It is possible to create chains of any length and since a promise can be resolved with another
 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
 * the promises at any point in the chain. This makes it possible to implement powerful apis like
 * $http's response interceptors.
 *
 *
 * # Differences between Kris Kowal's Q and $q
 *
 *  There are three main differences:
 *
 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
 *   mechanism in angular, which means faster propagation of resolution or rejection into your
 *   models and avoiding unnecessary browser repaints, which would result in flickering UI.
 * - $q promises are recognized by the templating engine in angular, which means that in templates
 *   you can treat promises attached to a scope as if they were the resulting values.
 * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
 *   all the important functionality needed for common async tasks.
 *
 *  # Testing
 *
 *

 *    it('should simulate promise', inject(function($q, $rootScope) {
 *      var deferred = $q.defer();
 *      var promise = deferred.promise;
 *      var resolvedValue;
 *
 *      promise.then(function(value) { resolvedValue = value; });
 *      expect(resolvedValue).toBeUndefined();
 *
 *      // Simulate resolving of promise
 *      deferred.resolve(123);
 *      // Note that the 'then' function does not get called synchronously.
 *      // This is because we want the promise API to always be async, whether or not
 *      // it got called synchronously or asynchronously.
 *      expect(resolvedValue).toBeUndefined();
 *
 *      // Propagate promise resolution to 'then' functions using $apply().
 *      $rootScope.$apply();
 *      expect(resolvedValue).toEqual(123);
 *    });
 *

 */
function $QProvider() {

  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
    return qFactory(function(callback) {
      $rootScope.$evalAsync(callback);
    }, $exceptionHandler);
  }];
}

/**
 * Constructs a promise manager.
 *
 * @param {function(function)} nextTick Function for executing functions in the next turn.
 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
 *     debugging purposes.
 * @returns {object} Promise manager.
 */
function qFactory(nextTick, exceptionHandler) {

  /**
   * @ngdoc
   * @name ng.$q#defer
   * @methodOf ng.$q
   * @description
   * Creates a `Deferred` object which represents a task which will finish in the future.
   *
   * @returns {Deferred} Returns a new instance of deferred.
   */
  var defer = function() {
    var pending = [],
        value, deferred;

    deferred = {

      resolve: function(val) {
        if (pending) {
          var callbacks = pending;
          pending = undefined;
          value = ref(val);

          if (callbacks.length) {
            nextTick(function() {
              var callback;
              for (var i = 0, ii = callbacks.length; i < ii; i++) {
                callback = callbacks[i];
                value.then(callback[0], callback[1]);
              }
            });
          }
        }
      },

      reject: function(reason) {
        deferred.resolve(reject(reason));
      },

      promise: {
        then: function(callback, errback) {
          var result = defer();

          var wrappedCallback = function(value) {
            try {
              result.resolve((callback || defaultCallback)(value));
            } catch(e) {
              exceptionHandler(e);
              result.reject(e);
            }
          };

          var wrappedErrback = function(reason) {
            try {
              result.resolve((errback || defaultErrback)(reason));
            } catch(e) {
              exceptionHandler(e);
              result.reject(e);
            }
          };

          if (pending) {
            pending.push([wrappedCallback, wrappedErrback]);
          } else {
            value.then(wrappedCallback, wrappedErrback);
          }

          return result.promise;
        }
      }
    };

    return deferred;
  };

  var ref = function(value) {
    if (value && value.then) return value;
    return {
      then: function(callback) {
        var result = defer();
        nextTick(function() {
          result.resolve(callback(value));
        });
        return result.promise;
      }
    };
  };

  /**
   * @ngdoc
   * @name ng.$q#reject
   * @methodOf ng.$q
   * @description
   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
   * used to forward rejection in a chain of promises. If you are dealing with the last promise in
   * a promise chain, you don't need to worry about it.
   *
   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
   * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
   * a promise error callback and you want to forward the error to the promise derived from the
   * current promise, you have to "rethrow" the error by returning a rejection constructed via
   * `reject`.
   *
   *

   *   promiseB = promiseA.then(function(result) {
   *     // success: do something and resolve promiseB
   *     //          with the old or a new result
   *     return result;
   *   }, function(reason) {
   *     // error: handle the error if possible and
   *     //        resolve promiseB with newPromiseOrValue,
   *     //        otherwise forward the rejection to promiseB
   *     if (canHandle(reason)) {
   *      // handle the error and recover
   *      return newPromiseOrValue;
   *     }
   *     return $q.reject(reason);
   *   });
   *

   *
   * @param {*} reason Constant, message, exception or an object representing the rejection reason.
   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
   */
  var reject = function(reason) {
    return {
      then: function(callback, errback) {
        var result = defer();
        nextTick(function() {
          result.resolve((errback || defaultErrback)(reason));
        });
        return result.promise;
      }
    };
  };

  /**
   * @ngdoc
   * @name ng.$q#when
   * @methodOf ng.$q
   * @description
   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
   * This is useful when you are dealing with an object that might or might not be a promise, or if
   * the promise comes from a source that can't be trusted.
   *
   * @param {*} value Value or a promise
   * @returns {Promise} Returns a promise of the passed value or promise
   */
  var when = function(value, callback, errback) {
    var result = defer(),
        done;

    var wrappedCallback = function(value) {
      try {
        return (callback || defaultCallback)(value);
      } catch (e) {
        exceptionHandler(e);
        return reject(e);
      }
    };

    var wrappedErrback = function(reason) {
      try {
        return (errback || defaultErrback)(reason);
      } catch (e) {
        exceptionHandler(e);
        return reject(e);
      }
    };

    nextTick(function() {
      ref(value).then(function(value) {
        if (done) return;
        done = true;
        result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
      }, function(reason) {
        if (done) return;
        done = true;
        result.resolve(wrappedErrback(reason));
      });
    });

    return result.promise;
  };

  function defaultCallback(value) {
    return value;
  }

  function defaultErrback(reason) {
    return reject(reason);
  }

  /**
   * @ngdoc
   * @name ng.$q#all
   * @methodOf ng.$q
   * @description
   * Combines multiple promises into a single promise that is resolved when all of the input
   * promises are resolved.
   *
   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
   *   each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of
   *   the promises is resolved with a rejection, this resulting promise will be resolved with the
   *   same rejection.
   */
  function all(promises) {
    var deferred = defer(),
        counter = 0,
        results = isArray(promises) ? [] : {};

    forEach(promises, function(promise, key) {
      counter++;
      ref(promise).then(function(value) {
        if (results.hasOwnProperty(key)) return;
        results[key] = value;
        if (!(--counter)) deferred.resolve(results);
      }, function(reason) {
        if (results.hasOwnProperty(key)) return;
        deferred.reject(reason);
      });
    });

    if (counter === 0) {
      deferred.resolve(results);
    }

    return deferred.promise;
  }

  return {
    defer: defer,
    reject: reject,
    when: when,
    all: all
  };
}
<|endoftext|>


<commit_before>app.controller("SegmentController", ["$scope", "$uibModal", "SegmentService", function($scope, $uibModal, SegmentService) {
	//add as needed will come back to add doing of off bradly history on organization
	$scope.segments = [0.0, 0.0];
	$scope.alerts = [];
	$scope.numSegments = 2;

	//get segments from api
	//come back for other gets
	// make doc blocks better

	$scope.getSegmentId = function(segmentId, validated ) {
		if (validated === true ) {
			SegmentService.fetchId(segmentId)
				.then(function(result){
					if(result.data.status === 200) {
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}

	};

	$scope.getSegmentStart = function(segmentStart, validated) {
		if (validated === true) {
			SegmentService.fetchSegmentStart(segmentStart)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getSegmentStop = function(segmentStop, validated) {
		if (validated === true) {
			SegmentService.fetchSegmentStop(segmentStop)
				.then(function(result){
					if(result.data.status === 200) {
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getElevationX = function(elevationX, validated) {
		if (validated === true) {
			SegmentService.fetchElevationX(elevationX)
				.then(function(result) {
					if(result.data.status === 200){
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}

	};
	$scope.getElevationY = function(elevationY, validated) {
		if (validated === true) {
			SegmentService.fetchElevationY(elevationY)
				.then(function(result) {
					if(result.data.status === 200){
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger",  msg: result.data.message}
					}
				});
		}
	};

	//create new segment
	$scope.createSegment = function(segment, validated) {
		if(validated === true) {

			SegmentService.create(segment)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}

				});
		}
	};

	//update the organization
	$scope.updateSegment = function(segment, validated) {
		if(validated === true && $scope.isEditing === true) {
			//this line of code is violating type hinting why?
			SegmentService.update(segment.Id, segment)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

	// temporary: load the array with blank values
	$scope.loadArray = function() {
		$scope.segments.length = 0;
		for(var i = 0; i < $scope.numSegments; i++) {
			$scope.segments.push([0.0, 0.0]);
		}
	};

	if($scope.segments.length === 0) {
		$scope.loadArray();
	}

}]);<commit_msg>working on George's segment template<commit_after>app.controller("SegmentController", ["$scope", "$uibModal", "SegmentService", function($scope, $uibModal, SegmentService) {
	//add as needed will come back to add doing of off bradly history on organization
	$scope.segments = [0.0, 0.0];
	$scope.alerts = [];
	$scope.numSegments = 2;

	//get segments from api
	//come back for other gets
	// make doc blocks better

	$scope.getSegmentId = function(segmentId, validated ) {
		if (validated === true ) {
			SegmentService.fetchId(segmentId)
				.then(function(result){
					if(result.data.status === 200) {
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	//comment here
	$scope.getSegmentStart = function(segmentStart, validated) {
		if (validated === true) {
			SegmentService.fetchSegmentStart(segmentStart)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getSegmentStop = function(segmentStop, validated) {
		if (validated === true) {
			SegmentService.fetchSegmentStop(segmentStop)
				.then(function(result){
					if(result.data.status === 200) {
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getElevationX = function(elevationX, validated) {
		if (validated === true) {
			SegmentService.fetchElevationX(elevationX)
				.then(function(result) {
					if(result.data.status === 200){
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}

	};
	$scope.getElevationY = function(elevationY, validated) {
		if (validated === true) {
			SegmentService.fetchElevationY(elevationY)
				.then(function(result) {
					if(result.data.status === 200){
						$scope.segments = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger",  msg: result.data.message}
					}
				});
		}
	};

	//create new segment
	$scope.createSegment = function(segment, validated) {
		if(validated === true) {

			SegmentService.create(segment)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}

				});
		}
	};

	//update the organization
	$scope.updateSegment = function(segment, validated) {
		if(validated === true && $scope.isEditing === true) {
			//this line of code is violating type hinting why?
			SegmentService.update(segment.Id, segment)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

	// temporary: load the array with blank values
	$scope.loadArray = function() {
		$scope.segments.length = 0;
		for(var i = 0; i < $scope.numSegments; i++) {
			$scope.segments.push([0.0, 0.0]);
		}
	};

	if($scope.segments.length === 0) {
		$scope.loadArray();
	}

}]);<|endoftext|>


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

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTop = val;
      if(currentTime < duration) {
        setTimeout(animateScroll, increment);
      }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  };

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  domready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      if(inValidRange(nextOffset, limit)) {
        my_removeClass(element, 'disabled');
      } else {
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
        clipboard,
        notification;

      clipboard = new Clipboard(this);
      console.log("clipboard", this);

      var notify = function(clipboardNotification, notificationText) {
        console.log(clipboardNotification);
        console.log(document.getElementById(clipboardNotification));
        notification = $($(clipboardNotification));
        console.log(notification);
        notification.text(notificationText);
        notification.addClass('in').delay(1400).queue(function() {
          notification.removeClass('in');
          $(this).dequeue();
        })
      };

      var notifySuccess = function(e) {
        notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
        //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
        notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;

      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });
    })

    each(document.querySelectorAll('[data-moment]'), function(el) {
      var time = moment(parseInt(el.textContent));
      el.textContent = time.fromNow();
    });
  });

})();
<commit_msg>changing clipboard<commit_after>(function() {
  'use strict';

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function my_addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function my_removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

  function scrollTop(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTop = val;
      if(currentTime < duration) {
        setTimeout(animateScroll, increment);
      }
    };
    animateScroll();
  }

  //t = current time
  //b = start value
  //c = change in value
  //d = duration
  Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
  };

  function each(o, cb, s){
    var n;
    if (!o){
      return 0;
    }
    s = !s ? o : s;
    if (o instanceof Array){
      // Indexed arrays, needed for Safari
      for (n=0; n<o.length; n++) {
        if (cb.call(s, o[n], n, o) === false){
          return 0;
        }
      }
    } else {
      // Hashtables
      for (n in o){
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false){
            return 0;
          }
        }
      }
    }
    return 1;
  };

  domready(function() {
    var
      scrollElements,
      inValidRange,
      setVisibility,
      setVisibilityAll,
      resetScroll;

    scrollElements = document.querySelectorAll('[data-scroll-element]');

    inValidRange = function(offset, limit) {
      return offset >= 0 && offset < limit;
    };

    setVisibility = function(element, nextOffset, limit) {
      if(inValidRange(nextOffset, limit)) {
        my_removeClass(element, 'disabled');
      } else {
        my_addClass(element, 'disabled');
      }
    };

    setVisibilityAll = function(elements, newOffset) {
      var
        scrollElement,
        increment,
        nextOffset,
        limit;

      each(elements, function(el) {
        scrollElement = document.querySelector(el.dataset.scrollElement);
        increment  = parseInt(el.dataset.scrollIncrement);
        nextOffset = newOffset + increment;
        limit      = parseInt(scrollElement.dataset.scrollLimit);

        setVisibility(el, nextOffset, limit);
      });
    };

    resetScroll = function(element) {
      element.scrollTop = 0;
      element.dataset.scrollOffset = 0;
    };

    $('[data-clipboard-target]').each(function() {
      var
        clipboard,
        notification;

      clipboard = new Clipboard(this);
      console.log("clipboard", this);

      var notify = function(clipboardNotification, notificationText) {
        console.log(document.getElementById(clipboardNotification.slice(1)));
        notification = $($(clipboardNotification));
        console.log(notification);
        notification.text(notificationText);
        notification.addClass('in').delay(1400).queue(function() {
          notification.removeClass('in');
          $(this).dequeue();
        })
      };

      var notifySuccess = function(e) {
        notify(e.trigger.dataset.clipboardNotification, "Copied!");
      };

      var notifyFailure = function(e) {
        //if the copy function failed the text should still be selected, so just ask the user to hit ctrl+c
        notify(e.trigger.dataset.clipboardNotification, "Press Ctrl+C to copy");
      };

      clipboard.on('success', notifySuccess);
      clipboard.on('error', notifyFailure);
    });

    each(scrollElements, function(el) {
      var
        element,
        increment,
        limit,
        offset,
        nextOffset,
        newOffset;

      element = document.querySelector(el.dataset.scrollElement);
      increment = parseInt(el.dataset.scrollIncrement);
      limit     = parseInt(element.dataset.scrollLimit.valueOf());
      offset    = parseInt(element.dataset.scrollOffset.valueOf());

      element.dataset.scrollLimit = limit;

      nextOffset = offset + increment;

      setVisibility(el, nextOffset, limit);

      // Force IE to forget previous scroll top value
      resetScroll(element);

      el.addEventListener('click', function() {
        offset = parseInt(element.dataset.scrollOffset);

        newOffset = offset + increment;

        if (inValidRange(newOffset, limit)) {
          scrollTop(element, document.getElementById(newOffset).offsetTop, 400);
          element.dataset.scrollOffset = newOffset;

          setVisibilityAll(scrollElements, newOffset);
        }
      });
    })

    each(document.querySelectorAll('[data-moment]'), function(el) {
      var time = moment(parseInt(el.textContent));
      el.textContent = time.fromNow();
    });
  });

})();
<|endoftext|>